JS Tidbit: A neat trick to compose arrays with conditional items using filter(Boolean)
Arnel Enero
Posted on July 31, 2022
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);
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.
💖 💪 🙅 🚩
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.