JavaScript Array lastIndexOf() Tutorial

In this section, we will learn what the lastIndexOf() method is and how to use it in JavaScript.

JavaScript Arrays lastIndexOf() Method

The `lastIndexOf()` method is used to find the index number of the last occurrence of an element in an Array object.

Array lastIndexOf() Syntax:

array.lastIndexOf(item, start)

Array lastIndexOf() Method Parameters:

The lastIndexOf() method takes two arguments:

  • The first argument is the element that we want to find its index number.
  • The second argument is the position from which the search should start.

Note: by default, the execution engine starts from the index 0 of the target array.

Array lastIndexOf() Method Return Value:

If the element is in fact in the target array, the return value of the method will be the index number of the last occurrence of that element. But if the element doesn’t exist in the target array, the return value of the method will be -1.

Example: using Array lastIndexOf() method in JavaScript

const arr = ["Apple","Google","Microsoft", "Apple","Tesla"];

console.log(arr.indexOf("Apple"));

console.log(arr.lastIndexOf("Apple"));

Output:

0

3

Leave a Reply