JavaScript Array findLast() Method
Example
Find the value of the last element whose value is greater than 18:
const
ages
=
[
3
,
10
,
18
,
20
]
;
function
checkAge
(
age
)
{
return
age
18
;
}
function
myFunction
(
)
{
document
.
getElementById
(
"
demo
"
)
.
innerHTML
=
ages
.
findLast
(
checkAge
)
;
}
Output result:
2
Try it »
Definition and Usage
The findLast() method returns the value of the last element that passes the condition.
The findLast() method executes a function for each element in the array.
If no matching element is found, the findLast() method returns undefined.
For empty array elements, the findLast() method does not execute the function.
The findLast() method does not change the original array.
Array search methods:
| Method | Description |
|---|---|
indexOf() |
Find the index of the first element with the specified value |
lastIndexOf() |
Find the index of the last element with the specified value |
find() |
Find the value of the first element that passes the test |
findIndex() |
Find the index of the first element that passes the test |
findLast() |
Find the value of the last element that passes the test |
findLastIndex() |
Find the index of the last element that passes the test |
Browser support
findLast() is a feature of ES2023.
Since July 2023, all modern browsers support this feature:
| Chrome 110 | Edge 110 | Firefox 115 | Safari 16.4 | Opera 96 |
| Feb 2023 | Feb 2023 | Jul 2023 | Mar 2023 | May 2023 |
Syntax
array.findLast(function(currentValue, index, arr), thisValue)
Parameters
| Parameters | Description |
|---|---|
| function | Required. The function to 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 that the current element belongs to. |
| thisValue | Optional, defaults to undefined. Passed as the this value of the function. |
Return Value
| Type | Description |
|---|---|
| Value | The value of the last element that passes the condition; if not found, returns undefined. |
Find the value of the last element whose value is greater than the specified number:
Example
<
p
<
input type
=
"number"
id
=
"ageToCheck"
value
=
"18"
p
<
button onclick
=
"myFunction()"
Try
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
)
;
}
Try it »
JavaScript Array object