JavaScript Array findLast()

Example 1

Find the value of the last element with a value over 18:

const ages = [3, 10, 18, 20];

function checkAge(age) {
  return age > 18;
}

function myFunction() {
  document.getElementById("demo").innerHTML = ages.findLast(checkAge);
}
Try it Yourself »

Description

The findLast() method returns the value of the last element that passes a test.

The findLast() method executes a function for each array element.

The findLast() method returns undefined if no elements are found.

The findLast() method does not execute the function for empty elements.

The findLast() method does not change the original array.


Array Find Methods:

MethodFinds
indexOf()The value of the first element with a specified value
lastIndexOf()The index of the last element with a specified value
find()The value of the first element that passes a test
findIndex()The index of the first element that passes a test
findLast()The value of the last element that passes a test
findLastIndex()The index of the last element that passes a test

Syntax

array.findLast(function(currentValue, index, arr),thisValue)

Parameters

function() Required.
A 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 of the current element.
thisValue Optional. Default undefined.
A value passed to the function as its this value.

Return Value

Type Description
A value The value of the last element that pass the test.
Otherwise it returns undefined.

Example 2

Find the value of the last element with a value above a specific 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>
Try it Yourself »


Browser Support

find() is an ES2023 feature.

It is supported in all modern browsers since July 2023:

Chrome 110 Edge 110 Firefox 115 Safari 16.4 Opera 96
Feb 2023 Feb 2023 Jul 2023 Mar 2023 May 2023

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.