Array.prototype.lastIndexOf()
lastIndexOf(searchElement, fromIndex) Returns:
number · Added in vES5 · Updated March 13, 2026 · Array Methods array index search
The lastIndexOf() method returns the last index at which a given element can be found in an array. If the element is not found, it returns -1.
How It Differs from indexOf()
const colors = ['red', 'blue', 'green', 'blue', 'yellow'];
colors.indexOf('blue'); // 1 (first occurrence)
colors.lastIndexOf('blue'); // 3 (last occurrence)
Strict Equality Comparison
lastIndexOf() uses strict equality (===) to compare elements. This means type coercion does not occur:
const mixed = [1, '1', true, 'true'];
mixed.lastIndexOf(1); // 0 (number)
mixed.lastIndexOf('1'); // 1 (string)
mixed.lastIndexOf(true); // 2 (boolean)
The fromIndex Parameter
The optional second parameter fromIndex specifies the starting position for the backward search. By default, it searches from the end of the array.
Important behavior:
- When
fromIndexis omitted, search starts fromarr.length - 1 - A positive
fromIndexcounts forward from the start - A negative
fromIndexcounts backward from the end
const letters = ['a', 'b', 'c', 'b', 'a', 'b'];
// Search from the end (default)
letters.lastIndexOf('b'); // 5
// Start searching backwards from index 3
letters.lastIndexOf('b', 3); // 3
// Negative fromIndex: start from 2 positions before the end
letters.lastIndexOf('b', -2); // 3
Examples
Finding the Last Occurrence
const sentence = 'the quick brown fox jumps over the lazy dog';
const chars = sentence.split('');
// Find last 'o'
const lastO = chars.lastIndexOf('o');
console.log(lastO); // 43
console.log(chars[lastO]); // 'o'
Limiting Search Range with fromIndex
const items = ['apple', 'banana', 'cherry', 'banana', 'date'];
// Find 'banana' before index 3 (exclusive)
const index = items.lastIndexOf('banana', 2);
console.log(index); // 1
Detecting Duplicate Elements
function hasDuplicate(arr) {
const unique = new Set(arr);
return unique.size !== arr.length;
}
function findDuplicates(arr) {
const duplicates = [Global_Objects::eval];
for (let i = 0; i < arr.length; i++) {
// If current index equals lastIndexOf, it's the last occurrence
// Check if we've already found this element earlier
if (arr.indexOf(arr[i]) !== i) {
if (!duplicates.includes(arr[i])) {
duplicates.push(arr[i]);
}
}
}
return duplicates;
}
console.log(hasDuplicate([1, 2, 3, 4])); // false
console.log(hasDuplicate([1, 2, 2, 3])); // true
console.log(findDuplicates([1, 2, 3, 2, 4])); // [2]
Notes
- Returns
-1when the element is not found - Empty arrays always return
-1 fromIndexdoes not change which index is returned—it only limits where the search begins
See Also
Array.prototype.indexOf()— Find the first occurrence of an elementArray.prototype.includes()— Check if array contains an element