lastIndexOf() Method in JavaScript
•JavaScript•2 min read

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
lastIndexOf()method in JavaScript is used to find the index of the last occurrence of a specified value in anarray. - 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
-1.
Example:
- Let's take an array
nameswith some duplicate names.
const names = ['john', 'max', 'alex', 'tony', 'smith', 'tony', 'jack'];- To find the last occurrence of
tonyin the array, use thelastIndexOf()method:
const indexNo = names.lastIndexOf('tony');
console.log(indexNo);
// Output:
5The search starts from the end of the array and returns 5 because the last occurrence of tony is at index 5.
- Now, if you provide a
from-indexvalue, the search starts from that index and searches backward.
const indexNo = names.lastIndexOf('tony', 4);
console.log(indexNo);
// Output:
// 3With from-index set to 4, the search starts from index 4 and finds the last occurrence of tony at index 3.
- The
lastIndexOf()method helps in finding the last occurrence of a value, optionally from a specified starting point.



