Array.prototype.findLast()
The backwards halves of find and findIndex. Before ES2023 the idiom was to reverse a copy and correct the index by hand, which is exactly the arithmetic these remove.
Demo
Both walk the array from the END towards the start and stop at the first element that passes. In [1, 2, 3, 4] the last element below 3 is the 2 at index 1 — so findLast gives 2 and findLastIndex gives 1. Note that the index is still measured from the left; only the scan direction reversed. The two no-match cases show the different failure values: undefined for the element form, -1 for the index form.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| callback | Function | yes | Called as callback(element, index, array), starting at the last element and working backwards. Iteration stops at the first truthy result. |
| thisArg | any | no (undefined) | Value of `this` inside the callback. Ignored for arrow functions. |
Return value
any | number — findLast returns the last matching ELEMENT, or undefined. findLastIndex returns its POSITION, or -1. Everything else about them is identical.
Common patterns
const latest = events.findLast(e => e.type === "error");
const end = items.findLastIndex(x => x != null); const trimmed = items.slice(0, end + 1);
const i = items.length - 1 - [...items].reverse().findIndex(pred);
Examples
Pitfalls
[1, 2, 3, 4].findLastIndex(x => x < 3)
items.length - 1 - items.findLastIndex(pred)
const n = [0, 1].findLast(x => x === 0); if (!n) { /* "not found" */ }
if (items.findLastIndex(pred) !== -1) { ... }
items.findLast(pred)
[...items].reverse().find(pred)
When to use
- The most recent entry in an append-ordered array
- Trimming or bounding from the end
- Any search where the last match matters rather than the first
- You want the FIRST match → find or findIndex
- You are matching a plain value → lastIndexOf
- Runtimes older than ES2023 → reverse a copy
Notes
FAQ
Because it returns a position, and positions in JavaScript arrays are always left-counted — that is what makes the result usable directly with bracket notation or slice. Only the search order is reversed.
const i = items.findLastIndex(pred); items[i]; // works directly