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.
const letters = ["a", "b", "a", "c"]; letters.lastIndexOf("a"); // 2
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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 findsNaN(becauseNaN !== NaN). Useincludes()to test forNaN, orfindLastIndex()withNumber.isNaN. - Objects are compared by reference. An equal-looking object literal is a different object and will not be found.
fromIndexmoves backward. The search covers the elements fromfromIndexdown to0. A negativefromIndexis added to the length, so-2means "start at the second-to-last element". If it is still negative after adding the length, the result is-1.- A
fromIndexlarger 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 findundefinedin a hole. - Need a condition instead of a value? Use
findLastIndex()(orfindLast()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.