The findLast() method in JavaScript is used to return the value of the last element in an array that satisfies the provided testing function. It does not modify the original array.
Syntax
array.findLast(callback(element, index, array), thisArg);
Parameters
Parameter | Description |
---|---|
callback | A function to test each element of the array. It takes three arguments: element, index, and array. |
element | The current element being processed in the array. |
index (Optional) | The index of the current element being processed in the array. |
array (Optional) | The array findLast() was called upon. |
thisArg (Optional) | A value to use as this when executing the callback function. |
Return Value
Return Type | Description |
---|---|
Any | The value of the last element that satisfies the provided testing function. |
Example 1: Finding the Last Even Number
This code demonstrates how to use the findLast()
method to find the last even number in an array.
let arr = [1, 3, 5, 7, 8, 10]; let lastEvenNumber = arr.findLast(function(element) { return element % 2 === 0; }); console.log(lastEvenNumber);
Output:
10
Example 2: Using Arrow Function
This code uses an arrow function to achieve the same result as the previous example.
let numbers = [1, 3, 5, 7, 8, 10]; let lastEvenNumber = numbers.findLast(element => element % 2 === 0); console.log(lastEvenNumber);
Output:
10
Example 3: Finding an Object in an Array
This code demonstrates how to use the findLast()
method to find an object in an array based on a specific property value.
let products = [ { id: 1, name: "Product 1" }, { id: 2, name: "Product 2" }, { id: 3, name: "Product 3" }, { id: 2, name: "Product 4" } ]; let lastProduct = products.findLast(element => element.id === 2); console.log(lastProduct);
Output:
{ id: 2, name: "Product 4" }
Example 4: Using a Provided thisArg
This code demonstrates how to use the findLast()
method with a provided thisArg
to access a variable outside the callback function.
let fruits = ["apple", "banana", "cherry"]; let findByLength = function(element) { return element.length === this.length; }; let lastFruit = fruits.findLast(findByLength, { length: 6 }); console.log(lastFruit);
Output:
"banana"
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
97 | 97 | 104 | 83 | 15.4 |