JavaScript findLast and findLastIndex Explained
Modern JavaScript introduced Array.prototype.findLast
and Array.prototype.findLastIndex as part of ECMAScript
2023 (ES14) to simplify the process of searching through arrays in
reverse order. These methods allow developers to find the last matching
element or the index of the last matching element in an array without
altering the original data or creating redundant copies.
The Problem with Previous Approaches
Prior to the introduction of these methods, searching an array from right to left required workarounds that were either inefficient or overly verbose:
- Reversing the array: Using
array.reverse().find()mutated the original array in place. - Cloning and reversing: Using
[...array].reverse().find()avoided mutation but introduced performance overhead by allocating a new array in memory. - Manual loops: Writing a reverse
forloop achieved the desired result efficiently, but increased boilerplate and reduced code readability.
findLast and findLastIndex solve these
issues by iterating from the end to the beginning natively and
efficiently.
Using Array.prototype.findLast
The findLast method iterates through the array in
reverse order and returns the value of the first element that satisfies
the provided testing function. If no elements satisfy the condition, it
returns undefined.
const numbers = [5, 12, 50, 130, 44, 25];
// Find the last number greater than 40
const lastLargeNumber = numbers.findLast((n) => n > 40);
console.log(lastLargeNumber); // Output: 44Using Array.prototype.findLastIndex
The findLastIndex method works identically to
findLast, but instead of returning the value, it returns
the index of the matching element. If no matching element is found, it
returns -1.
const transactions = [
{ id: 1, type: 'credit', amount: 100 },
{ id: 2, type: 'debit', amount: 50 },
{ id: 3, type: 'credit', amount: 200 },
{ id: 4, type: 'debit', amount: 25 },
];
// Find the index of the last credit transaction
const lastCreditIndex = transactions.findLastIndex((t) => t.type === 'credit');
console.log(lastCreditIndex); // Output: 2Key Advantages
- Readability: Expresses the developer’s intent directly without temporary variables or chained reverse calls.
- Performance: Executes in \(O(n)\) time without allocating new arrays, stopping execution as soon as a match is found.
- Immutability: Searches the array without modifying the original structure.