Trick: filter falsy values out of an array?


Lets say you need to filter all falsy


0, undefined, null, false, ''(empty string), NaN

values from array.

Of course you can use following construnction:




myArray

    .map(item => {

        // ...

    })

    // Get rid of falsy values

    .filter(item => item);





Since the values we don't want aren't truthy, the filter above removes those falsy items.

Did you know there's a clearer way with Boolean?




myArray

    .map(item => {

        // ...

    })

    // Get rid of falsy values

    .filter(Boolean);






Suhomozgy
Andrey

at JetRockets

Explore more of JetRockets