findLast() in JavaScript ES2023

The findLast() method offers a concise and efficient way to search arrays for elements that satisfy a specific condition, starting from the last element and iterating backward. This method returns the last matching element or undefined if no match is found.

Key benefits of findLast()

  • Efficiency: It stops iterating once a match is found, potentially saving processing time on larger arrays.
  • Readability: Provides a clear and concise way to find elements from the end, improving code readability.
  • Avoids manual reversal: Eliminates the need for manually reversing arrays or complex index calculations.

Example

const numbers = [1, 4, 2, 8, 5, 3];
const lastEvenNumber = numbers.findLast(number => number % 2 === 0);
console.log(lastEvenNumber); 

Output

JavaScript code example and output

Explantation

  1. We define an array of numbers containing various integers.
  2. We use findLast() on the numbers array, passing an arrow function as the callback.
  3. The callback number => number % 2 === 0 checks if the number is even.
  4. findLast() iterates through the array from the end, searching for the first element that satisfies the condition (being even).
  5. Since 8 is the last even number, it is returned as the result.

In a nutshell, findLast() can be a valuable tool for efficiently searching arrays from the end and finding the last matching element.