JavaScript find()
Method
Example
Get the first element in the array that is older than 18.
fruits output result:
18
Definition and Usage
The find()
method returns the value of the first element in the array that satisfies the provided testing function.
The find()
method executes the function once for each element present in the array:
When an element in the array satisfies the test condition and returns true,
find()
returns the element that passed the test and does not check the remaining values.If no elements satisfy the condition, it returns undefined.
Note: find()
does not execute the function for empty arrays.
Note: find()
does not change the original array.
Browser Support
The numbers in the table specify the first browser version that fully supports the method.
Method | Chrome | Edge | Firefox | IE | Safari |
---|---|---|---|---|---|
find() | 45.0 | 12.0 | 25.0 | 7.1 | 32.0 |
Note: find()
is not supported in IE 11 and earlier versions.
Syntax
array.find(function(currentValue, index, arr), thisValue)
Parameters
Parameter | Description |
---|---|
function(currentValue, index, arr) | Required. A function to be run for each element in the array. <br>Function parameters:<br> - currentValue: Required. The current element.<br> - index: Optional. The index of the current element.<br> - arr: Optional. The array object the current element belongs to. |
thisValue | Optional. A value to be passed to the function to be used as its "this" value. <br>If this parameter is empty, "undefined" will be passed as its "this" value. |
Technical Details
Return Value: | Returns the value of the first element in the array that satisfies the provided testing function. If no elements satisfy the condition, it returns undefined. |
---|---|
JavaScript Version: | ECMAScript 6 |
More Examples
Example
Return the index of the first array element that is greater than the number entered in the input field: