DEV Community

Arnel Enero
Arnel Enero

Posted on

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.

Top comments (3)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

.filter(x=>x) does exactly the same thing and is faster in some browsers.

Collapse
 
arnelenero profile image
Arnel Enero

True, there are a lot of possible predicates that achieve this same thing. It's a matter of personal preference which one is the best balance between readability and performance. Although in this case, unless we're composing an array with a lot of conditional items, performance differences would likely be insignificant.

Collapse
 
moopet profile image
Ben Sinclair

I'd say it's a little less readable though.