JavaScript Array find() function


The find() method of JavaScript is used to return the first elements value in an array, if the condition is passed, otherwise the return value is undefined. The syntax is as follows −

array.find(function(val, index, arr),thisValue)

Here, function is a function with val, which is the value of the current element. The index is the array index, and arr is the array. The this value parameter is the value to be passed to the function.

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
   <h2>Ranking Points</h2>
   <p>Get the points (first element) above 400...</p>
   <button onclick="display()">Result</button>
   <p id="demo"></p>
   <script>
      var pointsArr = [50, 100, 200, 300, 400, 500, 600];
      function pointsFunc(points) {
         return points > 400;
      }
      function display() {
         document.getElementById("demo").innerHTML = pointsArr.find(pointsFunc);
      }
   </script>
</body>
</html>

Output

Now, click on the “Result” button −

Let us see another example, wherein the result would be undefined −

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
   <h2>Ranking Points</h2>
   <p>Get the points (first element) above 400...</p>
   <button onclick="display()">Result</button>
   <p id="demo"></p>
   <script>
      var pointsArr = [50, 100, 200, 300, 400];
      function pointsFunc(points) {
         return points > 400;
      }
      function display() {
         document.getElementById("demo").innerHTML = pointsArr.find(pointsFunc);
      }
   </script>
</body>
</html>

Output

Now, click on the “Result” button −

Updated on: 17-Dec-2019

212 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements