Find the First Array Element matching a Condition in JS

avatar

Borislav Hadzhiev

Thu Nov 04 20212 min read

Find the First Array Element matching a Condition #

To find the first array element that matches a condition, call the find() method on the array, passing it a function. The find() method returns the first element, for which the test function returns a truthy value. If the function never returns a truthy value, undefined is returned.

index.js
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).

If the function we passed to the 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.

This is efficient, because we don't have to keep iterating over the array unnecessarily after we've found the item.

If the function never returns a truthy value, the find method will have to iterate over the entire array and return undefined.

index.js
const arr = [1, 2, 3, 4, 5]; const result = arr.find(element => { return element > 20000000; }); console.log(result); // ๐Ÿ‘‰๏ธ undefined

The condition we checked for in the function was never satisfied, so the find() method exhausted the elements in the array and returned undefined.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee