.findLastIndex()
Published Jul 6, 2023
Contribute to Docs
The .findLastIndex()
iterates through the array in reverse order and returns the index that passes the provided testing function. If no item passes, it returns -1
.
Syntax
array.findLastIndex((element, index) => {...});
The function can be invoked with two arguments:
element
: The current element in the iteration.index
(optional): The index of the array element.
Example
The following examples highlight the difference in how .findIndex()
and .findLastIndex()
iterate through an array:
let age = [13, 20, 15, 45, 1, 44, 80];console.log('findIndex() method: ');let findIndex = age.find((value, index) => {console.log('Checking age index: ', index);return value === 80;});
findIndex() method:Checking age index: 0Checking age index: 1Checking age index: 2Checking age index: 3Checking age index: 4Checking age index: 5Checking age index: 6
// Now .findLastIndex().age = [13, 20, 15, 45, 1, 44, 80];console.log('findLastIndex() method: ');findIndex = age.findLastIndex((value, index) => {console.log('Checking age index: ', index);return value === 80;});
findLastIndex() method:Checking age index: 6
Note: If an element is known to be at the end of an array, using
.findLastIndex
can shorten the iteration path.
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
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours