JavaScript find() | Find First Element that Satisfies 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 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 elements of array, until the given condition inside the function satisfies.

Note - The currentElementValue basically refers to a variable that will be used to pass as an argument to the function that of course indicates to the current value/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

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() returns undefined when no elements of specified array, satisfies the given condition.

JavaScript Online Test


« Previous Tutorial Next Tutorial »