JavaScript Array lastIndexOf() method

The lastIndexOf() method returns the last index (position) of a specified value.

The JavaScript array lastIndexOf() method is used to search the position of a particular element in a given array.

JavaScript Array lastIndexOf() method behaves similar to indexOf() method with a difference that it start searching an element from the last position of an array.

The lastIndexOf() method is case-sensitive.

Syntax

array.lastIndexOf(item, start)

Parameters: This method accepts two parameters as mentioned above and described below: 

item – Required. It represent the element to be searched.

start – It represent the index position from where search starts. It is optional.

The lastIndexOf() starts at a specified index and searches from right to left. By default the search starts at the last element and ends at the first.

start value greater than 0 is taken as the offset from the beginning of the array.

start value less than 0 is taken as the offset from the end of the array

Negative start values counts from the last element (but still searches from right to left).

The array is searched backwards, starting at start.

If the start is greater than or equal to the length of the array, the whole array will be searched. 

Return Value

The last index of the element in the array; -1 if not found.

Examples

Below are the examples of the Array lastIndexOf() method. 

const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];

console.log(animals.lastIndexOf('Dodo'));
// expected output: 3

console.log(animals.lastIndexOf('Tiger'));
// expected output: 1
var numbers = [2, 5, 9, 2];
numbers.lastIndexOf(2);     // 3
numbers.lastIndexOf(7);     // -1
numbers.lastIndexOf(2, 3);  // 3
numbers.lastIndexOf(2, 2);  // 0
numbers.lastIndexOf(2, -2); // 0
numbers.lastIndexOf(2, -1); // 3
var priceList = [10, 8, 2, 31, 10, 1, 65];

// lastIndexOf() returns the last occurance
var index1 = priceList.lastIndexOf(31);
console.log(index1); // 3

var index2 = priceList.lastIndexOf(10);
console.log(index2); // 4

// second argument specifies the backward search's start index
var index3 = priceList.lastIndexOf(10, 3);
console.log(index3); // 0

// lastIndexOf returns -1 if not found
var index4 = priceList.lastIndexOf(69.5);
console.log(index4); // -1