JavaScript find(): Find the first element that satisfies the given condition

The JavaScript find() method returns the first element from the specified array that satisfies the given condition. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>The first even number is: <span id="xyz"></span></p>
   
   <script>
      const numbers = [13, 32, 43, 54, 40];
      
      let firstEvenNum = numbers.find(even);

      function even(x)
      {
         return x%2==0;
      }

      document.getElementById("xyz").innerHTML = firstEvenNum;
   </script>
   
</body>
</html>
Output

The first even number is:

JavaScript find() syntax

The syntax of the find() method in JavaScript is:

array.find(functionName(currentElementValue, currentElementIndex, currentElementArray), thisValue)

The functionName and currentElementValue are required.

Note: The functionName refers to a function to execute for every element of the array until the given condition inside the function is satisfied.

Note: The currentElementValue basically refers to a variable that will be used as an argument to the function and that, of course, indicates the current value or element of the specified array.

Note: The currentElementIndex refers to the index of the current element.

Note: The currentElementArray refers to the array of the current element.

Note: The thisValue refers to a value passed to the specified function functionName as its this value. The default value is undefined.

JavaScript find() example

Consider the following code as an example demonstrating the find() method in JavaScript:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>Ignoring the first and last element<br>
      The first even number is: <span id="abc"></span></p>
   
   <script>
      const nums = [12, 33, 44, 54, 40];

      function findEven(x, indx, arr)
      {
         if(indx==0 || indx==(arr.length-1))
            return false;
      
         return x%2==0;
      }

      document.getElementById("abc").innerHTML = nums.find(findEven);
   </script>
   
</body>
</html>
Output

Ignoring the first and last element
The first even number is:

Note: The find() function returns undefined when no elements of the specified array satisfy the given condition.

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!