JavaScript Array find() Method


The JavaScript array find() method returns the first element of the given array that satisfies the provided function condition.

The JavaScript Array find() method returns the value of the first array element that satisfies the provided test function.

The find() method executes the function once for each element present in the array:

  • If it finds an array element where the function returns a true value, find() returns the value of that array element (and does not check the remaining values)
  • Otherwise it returns undefined

Parameters: This method accepts five parameters as mentioned above and described below:

  • function: It is the function of the array that works on each element.
  • currentValue: This parameter holds the current element.
  • index: It is an optional parameter that holds the index of current element.
  • arr: It is an optional parameter that holds the array object the current element belongs to.
  • thisValue: This parameter is optional, if a value to be passed to the function to be used as its “this” value else the value “undefined” will be passed as its “this” value.

Syntax

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

Example

Get the value of the first element in the array that has a value above a specific number:

<p>Minimum age: <input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">Try it</button>

<p>Any ages above: <span id="demo"></span></p>

<script>
var ages = [4, 12, 16, 20];

function checkAdult(age) {
  return age >= document.getElementById("ageToCheck").value;
}

function myFunction() {
  document.getElementById("demo").innerHTML = ages.find(checkAdult);
}
</script>

Example -