JavaScript Array lastIndexOf()

The lastIndexOf() method returns the index of the last occurrence of a specified element in the array.

Example

let priceList = [10, 8, 2, 31, 10, 31, 65];

// finding the index of the last occurence of 31 let lastIndex = priceList.lastIndexOf(31);
console.log(lastIndex); // Output: 5

lastIndexOf() Syntax

The syntax of the lastIndexOf() method is:

arr.lastIndexOf(searchElement, fromIndex)

Here, arr is an array.


lastIndexOf() Parameters

The lastIndexOf() method can take two parameters:

  • searchElement - The element to locate in the array.
  • fromIndex (optional) - The index to start searching backwards. By default it is array.length - 1.

lastIndexOf() Return Value

The lastIndexOf() method returns:

  • the last index of the element in the array if it is present at least once.
  • -1 if the element is not found in the array.

Note: lastIndexOf() compares searchElement to elements of the Array using strict equality (similar to triple-equals operator or ===).


Example 1: Using lastIndexOf() Method

let alphabets = ["a", "b", "c", "a", "d"];

// finding the index of the last occurence of 'a' let lastIndex1 = alphabets.lastIndexOf("a");
console.log(lastIndex1);
// finding the index of the last occurence of 'e' let lastIndex2 = alphabets.lastIndexOf("e");
console.log(lastIndex2);

Output

3
-1

In the above example, we have used the lastIndexOf() method to find the index of the last occurrence of 'a' and 'e'.

The last occurrence of 'a' is at index 3 in alphabets so alphabets.lastIndexOf("a") returns 3.

alphabets.lastIndexOf("e") returns -1 because the array does not contain 'e'.


Example 2: lastIndexOf() with two Parameters

let alphabets = ["a", "b", "c", "a", "d", "a"];

// second argument specifies the starting index // from where the method searches the element backward let lastIndex = alphabets.lastIndexOf("a", 4);
console.log(lastIndex);

Output

3

In the above example, we have passed the second argument 4 in the lastIndexOf() method.

alphabets.lastIndexOf("a", 4) searches the element 'a' backward from index 4 and returns the last occurrence of 'a' i.e. 3.


Example 3: lastIndexOf() with Negative Parameter

If fromIndex is a negative number then the index is calculated backward. For example:

let alphabets = ["a", "b", "c", "a", "d"];

// starts the search at third last position let lastIndex = alphabets.lastIndexOf("a", -3);
console.log(lastIndex);

Output

0

Here alphabets.lastIndexOf("a", -3) starts the search at third last position of the array and returns the last occurrence of 'a' which is 0.


Recommended Readings:

Did you find this article helpful?