2020-10-22
|~2 min read
|236 words
Truthiness in Javascript is always a fun topic to explore - particularly because it’s such a ripe area for pernicious bugs to sneak in. Fortunately, this is getting easier to manage with the introduction of the nullish coalesce.
One of the use cases for the nullish coalesce is as a fallback for a variable that doesn’t exist, which historically was done using the logical OR operator (||
). For example:
const foo = bar || ""
If bar evaluated to false, we would use the fallback value of the empty string.
Can you spot the potential problem here? We’re checking for falsey values, not, which is often desired null or undefined.
For example, imagine that 0
is a valid value, but the default should be 100
(yes, this is a contrived example):
const bar = 0
const foo = bar || 100
What is foo
? It’s 100
!
This is where nullish coalescing comes in. Instead of checking for truthiness, it only checks to see if something is defined (i.e. not null
or undefined
).
Using our same example as previously, but with nullish coalescing:
const bar = 0
const foo = bar ?? 100
Now, foo
is as expected, it’s 0
!
There are still good uses for the OR operator, but when it comes to fallbacks, I find nullish coalescing is almost always what I really want. It’s good it’s finally here!
Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!