Array.findLast()

The Array.findLast() method in JavaScript is used to return the last element in an array that satisfies a given testing function. This method executes the callback function for each element in reverse order (from right to left) and stops once it finds a match.

Syntax

</>
Copy
findLast(callbackFn)
findLast(callbackFn, thisArg)

Parameters

ParameterDescription
callbackFnA function used to test each element of the array. It takes three arguments: element (the current element being processed), index (the index of the current element), and array (the array findLast was called upon).
thisArg (Optional)An object to use as this when executing callbackFn.

Return Value

The findLast() method returns the last element in the array that satisfies the callbackFn. If no such element exists, it returns undefined.


Examples

1. Finding the Last Even Number

In this example, findLast() is used to find the last even number in an array.

</>
Copy
const numbers = [1, 3, 5, 8, 10, 13];

const result = numbers.findLast(num => num % 2 === 0);
console.log(result);

Output

10
  1. The callbackFn checks if the current number is even (i.e., divisible by 2).
  2. findLast() returns 10, the last even number in the array.

2. Using thisArg to Access External Context

The thisArg parameter allows you to pass an object as this inside the callbackFn.

</>
Copy
const numbers = [4, 9, 16, 25];
const threshold = { max: 15 };

const result = numbers.findLast(function(num) {
  return num < this.max;
}, threshold);

console.log(result);

Output

9
  1. The thisArg (threshold) provides an external context for callbackFn.
  2. findLast() returns 9, the last number less than threshold.max.

3. Returning undefined When No Match is Found

If no element satisfies the condition in callbackFn, findLast() returns undefined.

</>
Copy
const numbers = [1, 2, 3, 4];

const result = numbers.findLast(num => num > 10);
console.log(result);

Output

undefined

Since no element is greater than 10, the method returns undefined.

4. Using findLast() with Objects

The findLast() method can also be used to search for objects within an array.

</>
Copy
const users = [
  { id: 1, name: 'Akash' },
  { id: 2, name: 'Bhairav' },
  { id: 3, name: 'Charlie' },
];

const result = users.findLast(user => user.id < 3);
console.log(result);

Output

{ id: 2, name: 'Bhairav' }

Here, findLast() locates the last user object with an id less than 3.