JavaScriptArrays

Array.prototype.lastIndexOf()

Returns the index of the last occurrence of a value in the array, or -1 when it isn’t there.

Returns
The index of the last occurrence, or -1.
Changes the original
No
On this page

Example

#
JavaScript
const answers = ['A', 'C', 'B', 'C', 'D']

console.log(answers.lastIndexOf('C'))
console.log(answers.indexOf('C'))
console.log(answers.lastIndexOf('E'))
Console
3
1
-1

Definition and usage

#

The lastIndexOf() method searches the array from the end and returns the index of the last element equal to the given value. When that value isn’t there, the result is -1. The index is always counted from the start of the array, even though the search itself runs backward.

It compares strictly, like the === operator: the number 3 and the string "3" are different values to it, and NaN is never found. Objects are compared by reference, so to find an object by one of its fields, use findLastIndex() instead.

The second argument marks the index the search starts from, moving toward the beginning. That lets you find the second-to-last occurrence, or limit the search to the array’s early part.

Syntax

#
Syntax
array.lastIndexOf(searchElement)
array.lastIndexOf(searchElement, fromIndex)

Parameters

#
  • searchElement

    any value

    The value to search for.
  • fromIndex

    optional

    The index the search starts from, moving toward the beginning. Defaults to the last element. A negative value counts from the end.

More examples

#
Searching before the last occurrence
JavaScript
const logins = ['emma', 'jack', 'emma', 'mia', 'emma']

const last = logins.lastIndexOf('emma')
const previous = logins.lastIndexOf('emma', last - 1)

console.log(last, previous)
Console
4 2
Checking for duplicates
JavaScript
const tags = ['html', 'css', 'js', 'css']
const isUnique = (tag) => tags.indexOf(tag) === tags.lastIndexOf(tag)

console.log(isUnique('html'))
console.log(isUnique('css'))
Console
true
false
Pitfall: NaN
JavaScript
const values = [1, NaN, 3]

console.log(values.lastIndexOf(NaN))
console.log(values.findLastIndex(Number.isNaN))
Console
-1
1

lastIndexOf() compares with ===, and NaN isn’t even equal to itself. findLastIndex() can handle it with the Number.isNaN function.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Compare the result explicitly against -1. Index 0 is also a valid match, but it behaves like false in an if condition.
  • Comparing indexOf(x) === lastIndexOf(x) shows whether a value has no duplicates. Remember that for a value that isn’t there at all, both results are -1.

Related entries

#

Spotted a mistake or missing an example? Write to us.