Course contentsShow
← JavaScript
Lesson 881 of 2,72320. Array Iteration and TransformationFree lesson

Using findLast() and findLastIndex()

Learn about the ES2023 methods that search from the end of the array backward.

Using findLast() and findLastIndex()

What you'll learn: How to search arrays backward from the end using ES2023's findLast() and findLastIndex() methods.

The Core Idea

While find() and findIndex() search from the beginning of an array forward, sometimes you need to search from the end backward. ES2023 introduced findLast() and findLastIndex() for exactly this purpose. They work identically to their forward-searching counterparts, but start at the last element and move toward the first.

How They Work

findLast() returns the value of the last element that satisfies your test function:

const scores = [45, 78, 92, 88, 76, 95];

// Find the last score above 85
const lastHighScore = scores.findLast(score => score > 85);
console.log(lastHighScore); // 95

findLastIndex() returns the index of the last matching element:

const scores = [45, 78, 92, 88, 76, 95];

// Find the index of the last score above 85
const lastHighScoreIndex = scores.findLastIndex(score => score > 85);
console.log(lastHighScoreIndex); // 5

Why Use These?

Think of a log file where you want the most recent error, or a list where the newest entries are at the end. Instead of reversing the array or using filter() then grabbing the last item, you can search directly from the end:

const logs = ['info', 'warn', 'error', 'info', 'error'];

const lastErrorIndex = logs.findLastIndex(log => log === 'error');
console.log(lastErrorIndex); // 4 (the last 'error')

Both methods return undefined (for findLast()) or -1 (for findLastIndex()) when no match is found, just like their forward-searching siblings.

Key Takeaway: Use findLast() and findLastIndex() when you need to search arrays from the end backward—they're more efficient and clearer than reversing or filtering when you only care about the last matching element.