What is the nullish coalescing operator?
Consider the following JavaScript code:
id = id || generateId();
It's reasonable to write this with the assumption that generateId
will only run if id
is undefined
.
But this incorrect, and from experience, knowing that this is incorrect doesn't stop you from making the same mistake, repeatedly...
The ||
operator works as a loose falsy check, so this snippet actually says if id
is falsy, call and return generateId
.
A falsy value is any value that, when coerced to a Boolean
, returns false
. This includes undefined
and null
, as well as actual values like 0
and ""
:
Boolean(0); // falseBoolean(1); // trueBoolean(""); // falseBoolean("Wud up"); // true
A first attempt to fix our original code would be to refactor into a conditional that explicitly checks for undefined
:
if (id === undefined) {id = generateId();}
Or perhaps the same logic as a ternary operator:
id = id === undefined ? generateId() : id;
This would fix the most likely source of errors but we've lost the brevity of the original example. If we wanted to check for null
too, we'd certainly lose its clarity as well.
This is where the nullish coalescing (??
) operator comes in handy:
id = id ?? generateId();
The ??
operator only returns the second value if the first is undefined
or null
. It allows us to keep the original syntax, while allowing us to use 0
and ""
as real values (if that's what we want).
Browser support is great, and it's available from TypeScript 3.7, so you can already use the nullish coalescing operator in production!