JavaScript Array find()
Example 1
Find the value of the first element with a value over 18:
function checkAge(age) {
return age > 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.find(checkAge);
}
Description
Thefind() method returns the value of the first element that passes a test.
Thefind() method executes a function for each array element.
Thefind() method returnsundefined if no elements are found.
Thefind() method does not execute the function for empty elements.
Thefind() method does not change the original array.
Array Find Methods:
| Method | Finds |
|---|---|
| includes() | Returns true if an array contains a specified value |
| indexOf() | The index of the first element with a specified value |
| lastIndexOf() | The index of the last element with a specified value |
| find() | The value of the first element that passes a test |
| findIndex() | The index of the first element that passes a test |
| findLast() | The value of the last element that passes a test |
| findLastIndex() | The index of the last element that passes a test |
Syntax
Parameters
| function() | Required. A function to run for each array element. |
| currentValue | Required. The value of the current element. |
| index | Optional. The index of the current element. |
| arr | Optional. The array of the current element. |
| thisValue | Optional. Defaultundefined.A value passed to the function as its this value. |
Return Value
| Type | Description |
| A value | The value of the first element that pass the test. Otherwise it returns undefined. |
Example 2
Find the value of the first element with a value above a specific number:
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
const ages = [4, 12, 16, 20];
function checkAge(age) {
return age > document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.find(checkAge);
}
</script>
Array Tutorials:
Browser Support
find() is an ECMAScript6 (ES6 2015) feature.
JavaScript 2015 is supported in all browsers sinceJune 2017:
| Chrome 51 | Edge 15 | Firefox 54 | Safari 10 | Opera 38 |
| May 2016 | Apr 2017 | Jun 2017 | Sep 2016 | Jun 2016 |

