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
| Parameter | Type | Description |
|---|---|---|
| callbackFn | Function | A 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:
4The 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:
3Notes
Handier than reversing the array before find(): the array is neither changed nor copied.
See also
- Array.prototype.find — Returns the first element that passes a test.
- Array.prototype.findLastIndex — Returns the index of the last element that passes a test.
Related recipes
In the tutorial
- Searching arrays — How to find an element in a JavaScript array: includes, indexOf, find, findIndex, some and every.