JavaScript Array findLast()
- Previous page findIndex()
- Next page findLastIndex()
- Go back to the previous level JavaScript Array Reference Manual
Definition and usage
findLast()
The method returns the value of the last element that passed the test.
findLast()
The method executes a function for each array element.
If no elements are found,findLast()
The method returns undefined.
findLast()
The method does not execute the function for empty array elements.
findLast()
The method does not change the original array.
Array search methods:
Method | Search content |
---|---|
indexOf() | Index of the first element with the specified value. |
lastIndexOf() | Index of the last element with the specified value. |
find() | Value of the first element that passed the test. |
findIndex() | Index of the first element that passed the test. |
findLast() | The value of the last tested element. |
findLastIndex() | Index of the last element that passed the test. |
Instance
Example 1
Find the last element with a value greater than 18:
const ages = [3, 10, 18, 20]; function checkAge(age) { return age > 18; } function myFunction() { document.getElementById("demo").innerHTML = ages.findLast(checkAge); }
Example 2
Find the last element with a value greater than the specified number:
<p><input type="number" id="ageToCheck" value="18"></p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> const ages = [4, 12, 16, 20]; function checkAge(age) { return age > document.getElementById("ageToCheck").value; } function myFunction() { document.getElementById("demo").innerHTML = ages.findLast(checkAge); } </script>
Syntax
array.findLast(function(currentValue, index, arr), thisValue)
Parameters
Parameters | Description |
---|---|
function() | Required. The function run for each array element. |
currentValue | Required. The value of the current element. |
index | Optional. The index of the current element. |
arr | Optional. The array to which the current element belongs. |
thisValue |
Optional. The default value is undefined. The value of this passed to the function. |
Return Value
Type | Description |
---|---|
The value of the last tested element. If not found, it returns undefined. |
Browser Support
findLast()
It is a feature of ES2023.
Since July 2023, all modern browsers support this method:
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome 110 | Edge 110 | Firefox 115 | Safari 16.4 | Opera 96 |
February 2023 | February 2023 | July 2023 | March 2023 | May 2023 |
- Previous page findIndex()
- Next page findLastIndex()
- Go back to the previous level JavaScript Array Reference Manual