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)
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 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
.
// defining an arrayvar numbers = [12, 8, 2, 5, 12, 1, 20];// lastIndexOf() returns the last occurancevar index1 = numbers.lastIndexOf(5);console.log(index1); // 3var index2 = numbers.lastIndexOf(12);console.log(index2); // 4// specifying starting index of searchvar index3 = numbers.lastIndexOf(12, 3);console.log(index3); // 0// lastIndexOf returns -1 if not foundvar index4 = numbers.lastIndexOf(33);console.log(index4); // -1