Javascript Array - lastIndexOf() Method

Tutorialsrack 15/10/2022 Jquery Javascript

In this article, you will learn about the javascript Array built-in method Array.prototype.lastIndexOf(). How does this method work in javascript? 


This Array.prototype.lastIndexOf() method returns the last index at which a given element can be found in the array, otherwise, it returns -1 if the element is not present in an array. The array is searched right to left, starting at fromIndex.

array.lastIndexOf(searchElement, fromIndex);

This method takes 2 parameters as given below:

  • searchElement: This parameter holds the element to search in the array.
  • fromIndex(Optional):  This parameter holds the position in this array at which to begin searching for searchElement from backward. Negative fromIndex values count from the last element and it still searches from right to left. If the index is greater than or equal to the array's length, then it returns -1, which means the array will not be searched. 

You cannot use lastIndexOf() to search for empty slots in a sparse array, it returns -1.

Here are some examples of Array.prototype.lastIndexOf() method:

const arr = ['Java', 'C#', 'Python', 'SQL Server', 'GO', 'JavaScript'];

// Output => 2

console.log(arr.lastIndexOf("Python", 3))
// Output => 2

console.log(arr.lastIndexOf("Python", -1))
// Output => 2

//Sparse array
//You cannot use lastIndexOf() to search for empty slots in a sparse array, it returns -1.
const sparseArray = ['Java', , 'Python', , 'GO', 'JavaScript'];

// Output => -1

I hope this article will help you to understand the javascript Array built-in method Array.prototype.lastIndexOf()

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!

Related Posts


Recent Posts