JavaScriptArrays

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
On this page

Example

#
JavaScript
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))
Console
{ score: 55, passed: false }
3

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

#
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

    The this value 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

#

Spotted a mistake or missing an example? Write to us.