JS Tidbit: A neat trick to compose arrays with conditional items using filter(Boolean)

arnelenero

Arnel Enero

Posted on July 31, 2022

JS Tidbit: A neat trick to compose arrays with conditional items using filter(Boolean)

Just a quick tip that you might find useful with JavaScript...

When composing an array, we sometimes need to deal with items that are either:

  • potentially null or undefined, in which case we don't want to include it; or
  • should only be included if a certain condition is satisfied

Here's a neat trick to do that cleanly:

const list = [
  'A',
  somethingThatCanBeNullOrUndefined,
  condition && 'B'
].filter(Boolean);
Enter fullscreen mode Exit fullscreen mode

In the above example, .filter(Boolean) will pass each array item to the Boolean() constructor, which converts it to a boolean value (using JavaScript's truthy/falsy coercion).

Therefore, if somethingThatCanBeNullOrUndefined is null or undefined it becomes false and hence excluded by the filter. Similarly, if condition && 'B' short-circuits to false the item 'B' is excluded.

💖 💪 🙅 🚩
arnelenero
Arnel Enero

Posted on July 31, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related