The JavaScript array.findLast() method
The findLast() method returns the last element that passes your test, searching the array from the end backward, or undefined if none match. nums.findLast(n => n < 10) finds the last value under 10. It's the from-the-end counterpart of find().
Overview
findLast() works exactly like find() but searches from the end of the array toward the start, returning the first match it encounters that way — which is the last matching element in order. If nothing matches, you get undefined.
It saves you the awkward old workaround of reversing the array (or looping backward by hand) just to find the last item meeting a condition. The most recent log entry of a type, the last completed task, the final item below a threshold — all are one clean call.
Its index-returning partner is findLastIndex(), which gives the position instead of the element (or -1). Together, find()/findIndex() (from the start) and findLast()/findLastIndex() (from the end) cover searching by condition in either direction. The callback takes the usual element, index and array arguments.
Syntax
const element = array.findLast(callbackFn)
array.findLast((element, index, array) => {
return /* true for the element you want */;
})
[1, 8, 3, 9, 2].findLast(n => n < 5) // 2
Parameters
The array.findLast() method accepts the following parameters.
| Parameter | Description |
|---|---|
callbackFn |
Test run on elements from the end backward until one returns truthy. Receives (element, index, array). |
thisArg |
Optional. A value to use as this inside the callback. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const temps = [12, 18, 7, 21, 9];
const lastCold = temps.findLast(t => t < 10);
document.getElementById('out').textContent =
'last temp under 10: ' + lastCold; // 9
</script>
Best practices
- Use
findLast()to find the last element meeting a condition without reversing the array. - Use
findLastIndex()when you need the position of the last match instead. - For the first match (from the start), use find().
- Handle the
undefinedresult when nothing matches.
Frequently asked questions
What does findLast() do?
undefined if none match.What is the difference between find() and findLast()?
findLast() returns the last match (searching from the end).How do I get the index of the last match?
findLastIndex(), which returns the position (or -1).