JavaScript Array find()
- Previous Page filter()
- Next Page findIndex()
- Go to the Previous Level JavaScript Array Reference Manual
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); }
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>
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:
|
||||||||
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
- Previous Page filter()
- Next Page findIndex()
- Go to the Previous Level JavaScript Array Reference Manual