What is the lastIndexOf method in JavaScript Arrays?

lastIndexOf() is a built-in method that we can use with the Array type in JavaScript.

The following is the method prototype:

Array.lastIndexOf(searchElement, fromIndex)

Functionality

We use the lastIndexOf() method to find the position of an element in an array.

The method is similar to the indexOf() method, except that lastIndexOf() starts searching from the end of the array (unless otherwise specified) and moves backward.

The lastIndexOf() method

Parameters and return

The method takes the following input parameters:

  • searchElement: The element to to be searched within the array.

  • fromIndex: The index where the search will start. This is an optional parameter. If not otherwise specified, the search starts from the end of the array.

The lastIndexOf method returns the index of the last occurrence of the searchElement.

If the element is not found, the method returns -1.

Code

// defining an array
var numbers = [12, 8, 2, 5, 12, 1, 20];
// lastIndexOf() returns the last occurance
var index1 = numbers.lastIndexOf(5);
console.log(index1); // 3
var index2 = numbers.lastIndexOf(12);
console.log(index2); // 4
// specifying starting index of search
var index3 = numbers.lastIndexOf(12, 3);
console.log(index3); // 0
// lastIndexOf returns -1 if not found
var index4 = numbers.lastIndexOf(33);
console.log(index4); // -1
Copyright ©2024 Educative, Inc. All rights reserved