The findLast() method of the Array class in JavaScript returns the value of the last element in the array that satisfies the provided testing function. If no element satisfies the testing function, undefined is returned.
There are 2 variations for the syntax of Array.findLast() method. They are:
findLast(callbackFn)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
callbackFn | required | A function to test each element in the array. It takes three arguments: element, index, and array. |
This method returns the value of the last element in the array that satisfies the provided testing function.
Returns value of type Any
.
findLast(callbackFn, thisArg)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
callbackFn | required | A function to test each element in the array. It takes three arguments: element, index, and array. |
thisArg | optional | A value to use as this when executing callbackFn. |
This method returns the value of the last element in the array that satisfies the provided testing function, using thisArg as the value of this inside callbackFn.
Returns value of type Any
.
In JavaScript, we can use the findLast() method to find the last even number in an array.
For example,
const arr = [1, 3, 7, 8, 10];
const isEven = element => element % 2 === 0;
const lastEven = arr.findLast(isEven);
console.log(lastEven);
10
We can use the findLast() method to find the last string with length greater than 3 in an array.
For example,
const strArr = ['a', 'bc', 'def', 'ghij'];
const isLengthGreaterThanThree = element => element.length > 3;
const lastLongString = strArr.findLast(isLengthGreaterThanThree);
console.log(lastLongString);
ghij
We can use the findLast() method with a thisArg to find the last element in an array using a specific context.
For example,
const arr = [5, 12, 8, 130, 44];
const context = { threshold: 10 };
function isGreaterThanThreshold(element) {
return element > this.threshold;
}
const foundElement = arr.findLast(isGreaterThanThreshold, context);
console.log(foundElement);
44
In this JavaScript tutorial, we learned about findLast() method of Array: the syntax and few working examples with output and detailed explanation for each example.