JavaScript Array lastIndexOf() method
The lastIndexOf()
method in JavaScript is used to determine the index of the last occurrence of a specified element in an array. If the element is not found, it returns -1
. This method is case-sensitive and can be useful for searching through arrays from the end towards the beginning.
Syntax:
searchElement
: The element to search for in the array.fromIndex
(optional): The index at which to begin the search backwards. The default is the array's length minus one. If the specified index is greater than or equal to the array's length, the search starts from the end of the array.
Return Value:
- The index of the last occurrence of the specified element within the array, or
-1
if the element is not found.
Key Points:
- Case-sensitive: The search is case-sensitive for string elements.
- Returns the last index: If the element appears multiple times in the array,
lastIndexOf()
will return the index of the last occurrence. - Starts searching from a specified index: You can start searching from a specific index using the
fromIndex
parameter.
Example 1: Basic usage (Finding a number)
Example 2: Searching with a starting index
Example 3: Element not found
Example 4: Searching for a string with case sensitivity
Example 5: Using fromIndex
to search backwards
Example 6: Searching with negative fromIndex
Summary:
- The
lastIndexOf()
method is useful for searching for an element in an array and retrieving the index of its last occurrence. - It returns the index of the last occurrence of the specified element or
-1
if the element is not present, making it a valuable tool for reverse searching within arrays. - The optional
fromIndex
parameter allows for customized searching, including specifying a starting point from which to search backwards.