Open In App

JavaScript Array lastIndexOf() Method

The JavaScript Array lastIndexOf() Method is used to find the index of the last occurrence of the search element provided as the argument to the function.

Syntax: 



array.lastIndexOf(element, start)

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

Return value: This method returns the index of the last occurrence of the element. If the element cannot be found in the array, then this method returns -1.



Below is an example of the Array lastIndexOf() method. 

Example: 




let name = ['gfg', 'cse', 'geeks', 'portal'];
a = name.lastIndexOf('gfg')
 
// Printing result of method
console.log(a);

Output: 

0

Example 1: In this example, the method will be searched for element 2 in that array and return that element index. 




// Taking input as an array A
// having some elements.
let A = [1, 2, 3, 4, 5];
 
// lastIndexOf() method is called to
// test whether the searching element
// is present in given array or not.
a = A.lastIndexOf(2)
 
// Printing result of method.
console.log(a);

Output: 

1

Example 2: In this example, the method will search for the element 9 in that array if not found then return -1. 




// Taking input as an array A
// having some elements.
let name = ['gfg', 'cse', 'geeks', 'portal'];
 
// lastIndexOf() method is called to
// test whether the searching element
// is present in given array or not.
a = name.lastIndexOf('cat')
 
// Printing result of method
console.log(a);

Output: 

-1

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

Supported Browsers: The browsers supported by JavaScript Array lastIndexOf() method are listed below: 

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.


Article Tags :