JavaScript .lastIndexOf()
Published Oct 15, 2021Updated Jul 13, 2023
Contribute to Docs
The .lastIndexOf() array method returns the last index at which an element can be found. Otherwise, it returns -1 if the element is not found.
Syntax
array.lastIndexOf(searchElement, fromIndex);
searchElement: The target element in the search.fromIndex(optional): The starting index position that search begins. The default value offromIndexisarray.length - 1. Therefore, if undefined, the search starts from the last index.
Note: A negative
fromIndexwill offset from the end of the array to begin the search. The array is still searched backwards.
Examples
Searching for an element not in the given array:
const fruits = ['apple', 'orange', 'peach'];const lastIndexOfCherry = fruits.lastIndexOf('cherry');console.log(lastIndexOfCherry);// Output: -1
Searching for the element indigo in an array of colors:
const rainbow = ['red','orange','yellow','green','blue','indigo','violet',];const checkIndigo = rainbow.lastIndexOf('indigo');console.log(checkIndigo);// Output: 5
Codebyte Example
The example below defines a new array cities. The array lists the city 'Berlin' twice (multiple matches will only return the last index within the index range where a match occurs):
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
- Includes 34 Courses
- With Professional Certification
- Beginner Friendly.115 hours
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.15 hours