JavaScript Array lastIndexOf()

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

Example


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

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

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:

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: