EN
JavaScript - find first element of array matching boolean condition
0 points
In this article, we would like to show you how to find the first element of an array matching boolean condition using JavaScript.
In this example, we use find()
method with passed isDefined()
function to find the first element that is defined (that's not null
or undefined
).
xxxxxxxxxx
1
const array = [null, undefined, 'a', 'b', 'c'];
2
3
const isDefined = (element) => element !== null && typeof element !== 'undefined';
4
5
const result = array.find(isDefined);
6
7
console.log(result); // 'a'
Note:
The
find()
method has been introduced in ES6.