lastIndexOf() Array Method in JavaScript Explained
Whenever you use lastIndexOf() on an array, the method does the following:
- It searches its calling array for the method’s first argument.
- It returns the index position of the last match, or
-1
if the method found no match.
Syntax of the lastIndexOf()
Method
lastIndexOf()
accepts two arguments. Here is the syntax:
Argument 1: valueToFind
A valueToFind
is the first argument accepted by the lastIndexOf()
method. It defines the value you wish to find in the calling array.
Example 1: Find the index of the last Tuesday
Example 2: Find the index of the last Friday
Example 3: Find the index of the last 7
Argument 2: startIndex
The startIndex
argument is optional. It specifies the index position where you want the computer to start searching for the valueToFind
argument.
Keep in mind that lastIndexOf()
, by default, searches backward from a startIndex
of callingArray.length - 1
.
Therefore, if you omit the startIndex
argument, the search will begin from the last item in the calling array.
Example 1: Find the index of the last Tuesday
from the 6th index position
The snippet above returned 2
because the search started backward from the sixth index position.
However, suppose you omit the startIndex
argument. In that case, the computer will search backward from the last item in the calling array (callingArray.length - 1
).
Here’s an example:
Example 2: Find the index of the last Tuesday
from the negative 6th index position
Note that a negative startIndex
argument means that the computer should start its index count from the last item in the calling array. But JavaScript will still do a backward (right to left) search.
Suppose startIndex
is greater than the calling array’s length. In such a case, the computer will default to callingArray.length - 1
.
Here’s an example: