Today I Learned

This project exists to catalogue the sharing & accumulation of knowledge as it happens day-to-day. Posts have a 200-word limit, and posting is open to any Rocketeer as well as selected friends of JetRockets. We hope you enjoy learning along with us.

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);

Looking for help? At JetRockets, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.