Array.lastIndexOf()

The Array.lastIndexOf() method in JavaScript is used to find the last occurrence of a specified element in an array. It searches the array backward, starting at a specified index or the array’s end by default. If the element is not found, it returns -1.

Syntax

</>
Copy
lastIndexOf(searchElement)
lastIndexOf(searchElement, fromIndex)

Parameters

ParameterDescription
searchElementThe element to locate in the array.
fromIndex (optional)The index at which to start searching backward. Defaults to array.length - 1. If negative, it is taken as an offset from the end of the array.

Return Value

The lastIndexOf() method returns the last index at which the searchElement is found in the array. If the element is not found, it returns -1.


Examples

1. Finding the Last Occurrence of an Element

In this example, the method is used to locate the last occurrence of an element in the array.

</>
Copy
const fruits = ['apple', 'banana', 'cherry', 'apple', 'banana'];

console.log(fruits.lastIndexOf('banana'));
console.log(fruits.lastIndexOf('apple'));

Output

4
3
  1. fruits.lastIndexOf('banana') finds the last occurrence of 'banana' at index 4.
  2. fruits.lastIndexOf('apple') finds the last occurrence of 'apple' at index 3.

2. Using the fromIndex Parameter

The fromIndex parameter specifies the index at which to start searching backward.

</>
Copy
const numbers = [1, 2, 3, 2, 1];

console.log(numbers.lastIndexOf(2, 3));
console.log(numbers.lastIndexOf(2, 1));

Output

3
1
  1. numbers.lastIndexOf(2, 3) searches backward from index 3 and finds the last occurrence of 2 at index 3.
  2. numbers.lastIndexOf(2, 1) searches backward from index 1 and finds the last occurrence of 2 at index 1.

3. Negative fromIndex Value

A negative fromIndex value is treated as an offset from the end of the array.

</>
Copy
const colors = ['red', 'blue', 'green', 'blue'];

console.log(colors.lastIndexOf('blue', -2));
console.log(colors.lastIndexOf('red', -1));

Output

1
0
  1. colors.lastIndexOf('blue', -2) starts searching backward from index 2 (offset from the end) and finds 'blue' at index 1.
  2. colors.lastIndexOf('red', -1) searches backward from the last element and finds 'red' at index 0.

4. Element Not Found

If the element is not found in the array, lastIndexOf() returns -1.

</>
Copy
const animals = ['cat', 'dog', 'bird'];

console.log(animals.lastIndexOf('fish'));
console.log(animals.lastIndexOf('dog', -3));

Output

-1
-1
  1. animals.lastIndexOf('fish') returns -1 because 'fish' is not in the array.
  2. animals.lastIndexOf('dog', -3) returns -1 because 'dog' is not found when searching backward from the specified index.