Array. prototype. findLast()
Returns the last element that matches a condition, searching the array from the end.
- Returns
- The last matching element, or
undefined. - Changes the original
- No
Example
#const attempts = [
{ score: 40, passed: false },
{ score: 75, passed: true },
{ score: 55, passed: false },
{ score: 90, passed: true }
]
console.log(attempts.findLast((a) => !a.passed))
console.log(attempts.findLastIndex((a) => a.passed))Definition and usage
#The findLast() method works like find(), but starts from the last element and moves toward the start. It returns the first matching element it meets, which is the last one in the array’s order.
It’s useful for data laid out chronologically: the last message from a given person, the last failed attempt at a test, the most recent entry that matches a condition.
Its index-returning counterpart is findLastIndex(). Neither method reverses the array, so both are more efficient than [...array].reverse().find().
Syntax
#array.findLast(callbackFn)
array.findLast(callbackFn, thisArg)Parameters
#callbackFn
function (element, index, array)
The testing function, called starting from the end of the array.thisArg
optional
Thethisvalue inside the function.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Instead of reversing an array to find its last matching element, use
findLast(). You avoid making a copy and don’t mutate the data. - When you need the position, reach for
findLastIndex().
Related entries
#- Array.prototype.find()Returns the first element that matches a condition, or undefined.
- Array.prototype.findIndex()Returns the index of the first element that matches a condition, or -1.
- Array.prototype.at()Returns the element at the given index, which can also be counted from the end.
- Array.prototype.findLastIndex()Returns the index of the last element matching a condition, searching from the end, or -1.
Spotted a mistake or missing an example? Write to us.