• JavaScript Video Tutorials

JavaScript - Array findLast() Method



In JavaScript, the Array.findLast() method is used to iterate over the array elements in reverse order and returns the value of the first element that satisfies the provided function. If no element is satisfying the condition in provided function, it returns "undefined" as result.

This method does not execute the function for empty array elements. In addition to that, this method does not modify the original array.

The findLast() method is newly available mehtod since August 2022. This method works in lastest devices and browsers. It may not work in older devices or browsers.

Syntax

Following is the syntax of JavaScript Array.findLast() method −

findLast(callbackFn, thisArg)

Parameters

This method accepts two parameters. The same is described below −

  • callbackFn − A function to be executed for each element in the array. It takes three arguments −
    • 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 every() was called upon.
  • thisArg (optional) − A value to be passed to the function as its this value.

Return value

This mehtod returns the value of the last element that pass the provided testing function; Otherwise it is 'undefined'.

Examples

Example 1

In the following example, we are finding the last even number in the array using the JavaScript Array.findLastIndex() method −

<html>
<body>
   <script>
      const numbers = [1, 2, 3, 4, 5];
      const lastValue = numbers.findLast((num) => num % 2 === 0);
      document.write(lastValue);
   </script>
</body>
</html>

Output

It returns '4' as result because it is the last even number in the array.

4

Example 2

In the following example, we are finding the last string element in the array that starts with a specific letter ('a') −

<html>
<body>
   <script>
      const words = ['apple', 'banana', 'avocado', 'orange', 'grape'];
      const lastValue = words.findLast((word) => word.startsWith('a'));
      document.write(lastValue);
</script>
</body>
</html>

Output

It returns "avocado" as a result beacuse it is the last word that satisfies the condition.

avocado

Example 3

Here, we are finding the last element of the array which has a value greater than 10 −

<html>
<body>
   <script>
      const numbers = [5, 8, 12, 15, 20, 4];
      const lastValue = numbers.findLast((num) => num > 10);
      document.write(lastValue);
   </script>
</body>
</html>

Output

20

Example 4

In the below example, we are finding the last element in the array which is an even number −

<html>
<body>
   <script>
      const numbers = [1, 3, 5, 7, 9];
      const lastValue = numbers.findLast((num) => num % 2 === 0);
      document.write(lastValue);
   </script>
</body>
</html>

Output

It returns 'undefined' as result because, no element in the array satisfies the function.

undefined
Advertisements