JavaScript lastIndexOf()
The lastIndexOf()
method in JavaScript returns the last index of a specified search value within an array or string. This method compares the specified search value with elements in the array or string from right to left.
Syntax
The syntax of the lastIndexOf()
method is as follows:
array.lastIndexOf(searchValue[, fromIndex])
string.lastIndexOf(searchValue[, fromIndex])
searchValue
: The value to search for in the array or string.fromIndex
(Optional): The index to start searching from. By default, the search starts from the last index of the array or string.
Example
The following example demonstrates the usage of the lastIndexOf()
method:
const arr = [10, 20, 30, 40, 50];
const index = arr.lastIndexOf(30);
console.log(index); // Output: 2
const str = "Hello, World!";
const index = str.lastIndexOf("l");
console.log(index); // Output: 10
Output
The output of the above example will be:
2
10