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.
Top comments (3)
.filter(x=>x)
does exactly the same thing and is faster in some browsers.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.
I'd say it's a little less readable though.