JavaScript Array find()

Definition and Usage

find() The method returns the value of the first element in the array that passes the test (as the function provided).

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

  • If the find() function returns a true value for the array element found, it returns the value of the array element (and does not check the remaining values)
  • Otherwise, return undefined

Note:find() Do not execute the function on an empty array.

Note:find() Does not change the original array.

Instance

Example 1

Find the value of the first element in the array that is 18 or greater:

var ages = [3, 10, 18, 20];
function checkAdult(age) {
  return age >= 18;
}
function myFunction() {
  document.getElementById("demo").innerHTML = ages.find(checkAdult);
}

Try it yourself

Example 2

Get the value of the first element in the array whose value is higher than 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>

Try it yourself

Syntax

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

Parameter value

Parameter Description
function(currentValue, index, arr) Required. The function to be run for each element in the array.

Function parameters:

Parameter Description
currentValue Required. The value of the current element.
index Optional. The array index of the current element.
arr Optional. The array object to which the current element belongs.
thisValue

Optional. The value to be passed to the function as its 'this' value.

If this parameter is empty, the value 'undefined' will be passed as its 'this' value.

Technical details

Return value: If any element in the array passes the test, return the element value; otherwise, return undefined.
JavaScript version: ECMAScript 6

Browser support

The numbers in the table indicate the first browser version that fully supports this method.

Chrome Edge Firefox Safari Opera
Chrome 45 Edge 12 Firefox 25 Safari 7.1 Opera 32
September 2015 July 2015 July 2014 September 2014 September 2015

Note:Internet Explorer does not support find() Methods.

Related Pages

Tutorial:JavaScript Array

Tutorial:JavaScript Array Const

Tutorial:JavaScript Array Methods

Tutorial:JavaScript Array Sorting

Tutorial:JavaScript Array Iteration