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:

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: 44

Using 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: 2

Key Advantages