lastIndexOf() Method in JavaScript
•JavaScript

javascriptlastindexof methodarray methods
The lastIndexOf() method in JavaScript is used to find the index of the last occurrence of a specified value in an array.
lastIndexOf() Method in JavaScript
- The method in JavaScript is used to find the index of the last occurrence of a specified value in an .
- It returns the index of the last matching element.
- The search starts from the last index of the array but only shows the last occurrence.
- It takes two arguments:
- search-element: The value to search for.
- from-index (optional): The index from which to start the search. If not provided, it searches from the end of the array.
- If the element is not found, it returns .
Example:
- Let's take an array with some duplicate names.
1const names = ['john', 'max', 'alex', 'tony', 'smith', 'tony', 'jack'];- To find the last occurrence of in the array, use the method:
1const indexNo = names.lastIndexOf('tony');
2console.log(indexNo);
3
4
5
6// Output:
75The search starts from the end of the array and returns because the last occurrence of is at index .
- Now, if you provide a value, the search starts from that index and searches backward.
1const indexNo = names.lastIndexOf('tony', 4);
2console.log(indexNo);
3
4
5
6// Output:
7// 3With set to , the search starts from index and finds the last occurrence of at index .
- The method helps in finding the last occurrence of a value, optionally from a specified starting point.



