The JavaScript find function is utilized to retrieve the value of the initial element within an array that meets the specified criteria. The find function invokes the provided function on each element in the array sequentially. If the function returns a truthy value for an element, find will return that element and cease further checks on the remaining elements. If no elements satisfy the condition, it returns undefined.
- find does not perform the function on empty arrays.
- find does not modify the original array.
Syntax:
array.find(function(value, index, arr))
Parameters:
Value (mandatory): The value associated with the present element.
Index (optional): Refers to the position of the current element within the array.
Arr : The array instance to which the current element is associated.
Return value:
It provides the value of the array element if the elements meet the specified condition; if not, it results in an undefined value.
Browser Support:
| Chrome | 45.0 |
|---|---|
Edge |
7.1 |
| Firefox | 25.0 |
| Opera | 32.0 |
Example 1
JavaScript Array find Method
<script type="text/javascript">
// JavaScript to illustrate find() method
function Example(value)
{
return value >12;
}
// Input array
var arr = [1,2,3,4,5,6,7,8,9,12,11,14];
var result = arr.find(findFunction);
document.write(result)
// expected output: arr[Output:14]
</script>
Output:
Example 2
JavaScript Array find Method
<script type="text/javascript">
// JavaScript to illustrate find() method
function Example(value)
{
return value ==15;
}
// Input array
var arr = [1,2,3,4,5,6,7,8,9,12,11,14];
var result = arr.find(findFunction);
document.write(result)
// expected output: arr[Output: undefined]
</script>
Output:
Undefined