~2 min read|
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
This is where nullish coalescing comes in. Instead of checking for truthiness, it only checks to see if something is defined (i.e. not
Using our same example as previously, but with nullish coalescing:
const bar = 0 const foo = bar ?? 100
foo is as expected, it’s
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!