Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Array.prototype.findLast

Searches from the end of an array for the first element that passes a test.

Available since: ES2023

Syntax

array.findLast(callbackFn)

Parameters

ParameterTypeDescription
callbackFnFunctionA test function: receives the element, its index and the array, and returns true for a match.

Return value

anyThe last matching element, or undefined.

Examples

The last even number:

console.log([1, 2, 3, 4, 5].findLast((n) => n % 2 === 0));

Output:

4

The last order with the paid status:

const orders = [
  { id: 1, status: 'paid' },
  { id: 2, status: 'new' },
  { id: 3, status: 'paid' },
];
 
console.log(orders.findLast((order) => order.status === 'paid').id);

Output:

3

Notes

Handier than reversing the array before find(): the array is neither changed nor copied.

See also

Related recipes

In the tutorial

  • Searching arrays — How to find an element in a JavaScript array: includes, indexOf, find, findIndex, some and every.

Thanks for reading!

Donate to the site — we work hard for you.