Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Array

Array.prototype.lastIndexOf()

Reference for JavaScript Array.prototype.lastIndexOf(): find the last position of a value with strict equality, the fromIndex argument and the NaN pitfall.

The lastIndexOf() method searches an array from the end toward the start and returns the index of the last element that is strictly equal to the value you give it. If nothing matches, it returns -1.

It is the mirror image of indexOf(). Use it when duplicates are possible and you care about the final occurrence, for example the last separator in a list of path segments.

JavaScript
const letters = ["a", "b", "a", "c"];
letters.lastIndexOf("a"); // 2

Try it

JS Finding the last match

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Starting the search earlier

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
array.lastIndexOf(searchElement)
array.lastIndexOf(searchElement, fromIndex)
Name Description
searchElement The value to look for. It is compared with strict equality (===).
fromIndex Optional. The index where the backward search starts (that element is included). Defaults to array.length - 1. A negative value counts from the end.

Return value: the index of the last match, or -1 if none is found.

Exceptions: none for ordinary arrays.

Usage notes

  • Strict equality. lastIndexOf() uses ===, so it never finds NaN (because NaN !== NaN). Use includes() to test for NaN, or findLastIndex() with Number.isNaN.
  • Objects are compared by reference. An equal-looking object literal is a different object and will not be found.
  • fromIndex moves backward. The search covers the elements from fromIndex down to 0. A negative fromIndex is added to the length, so -2 means "start at the second-to-last element". If it is still negative after adding the length, the result is -1.
  • A fromIndex larger than the array is clamped to the last index.
  • No mutation. The array is not changed.
  • Holes: unlike includes(), it skips empty slots in sparse arrays, so it can never find undefined in a hole.
  • Need a condition instead of a value? Use findLastIndex() (or findLast() for the element itself).
  • Strings have their own lastIndexOf() that searches for substrings; the argument rules are different.

Browser support

Array.prototype.lastIndexOf() is part of ES5 and works in every browser in use today.