findLast() and findLastIndex()
You'll learn how to search arrays from the end without reversing them or writing manual backward loops.
The Problem with Searching Backwards
Sometimes you need the last element that matches a condition, not the first. Before ES2023, you'd have to reverse the array, use find(), then adjust indexes—or write a manual loop counting down. Both approaches felt clunky.
How findLast() Works
findLast() searches your array from right to left and returns the first match it encounters (which is the last match in normal left-to-right terms):
const scores = [45, 82, 67, 95, 73, 88];
// Find the last score above 80
const lastHighScore = scores.findLast(score => score > 80);
console.log(lastHighScore); // 88 (not 82 or 95)
It stops as soon as it finds a match when scanning backwards, returning that element's value.
How findLastIndex() Works
findLastIndex() does the same search but returns the index instead of the value:
const scores = [45, 82, 67, 95, 73, 88];
const lastHighIndex = scores.findLastIndex(score => score > 80);
console.log(lastHighIndex); // 5 (position of 88)
This is perfect when you need to know where the last matching item lives.
Why This Matters
Think of scanning a log file for the most recent error, or finding the last item a user modified. These methods let you express that intent clearly without gymnastics:
const logs = [
{ level: 'info' },
{ level: 'error' },
{ level: 'info' },
{ level: 'error' }
];
const lastError = logs.findLast(log => log.level === 'error');
// Returns the 4th object, not the 2nd
Key Takeaway: findLast() and findLastIndex() search arrays backwards, returning the rightmost match without reversing or manual loops—making "find the last occurrence" code clean and intuitive.