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
findLast(callbackFn)
findLast(callbackFn, thisArg)
Parameters
Parameter | Description |
---|---|
callbackFn | A 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.
const numbers = [1, 3, 5, 8, 10, 13];
const result = numbers.findLast(num => num % 2 === 0);
console.log(result);
Output
10
- The
callbackFn
checks if the current number is even (i.e., divisible by 2). findLast()
returns10
, 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
.
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
- The
thisArg
(threshold
) provides an external context forcallbackFn
. findLast()
returns9
, the last number less thanthreshold.max
.
3. Returning undefined
When No Match is Found
If no element satisfies the condition in callbackFn
, findLast()
returns undefined
.
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.
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
.