Borislav Hadzhiev
Last updated: Nov 4, 2021
Check out my new book
To find the first array element that matches a condition:
Array.find()
method to iterate over the array.find
method returns the first array element that satisfies the
condition.const arr = [1, 2, 3, 4, 5]; const result = arr.find(element => { return element > 2; }); console.log(result); // 👉️ 3
The function we passed to the Array.find method gets called with each element in the array until it returns a truthy value or iterates over the entire array.
Truthy values are all values that are not falsy.
The falsy values in JavaScript are: false
, null
, undefined
, 0
, ""
(empty string), NaN
(not a number).
find
method returns a truthy value at least once, the find
method short-circuits and returns the corresponding array element.In the example, we check if the current array element is greater than 2
. The
first element in the array that is greater than 2
is 3
.
As soon as the condition is met, the find
method short-circuits and returns
the value.
If the function never returns a truthy value, the find
method will have to
iterate over the entire array and will return undefined
.
const arr = [1, 2, 3, 4, 5]; const result = arr.find(element => { return element > 20000000; }); console.log(result); // 👉️ undefined
The implemented condition is never satisfied, so the find()
method iterated
over the entire array and ended up returning undefined
.