Also available in🇻🇳
Nullish Coalescing is a valuable addition in Javascript.
Represent as ??
format, it provides a streamlined approach for working with variables that may be assigned null
or undefined
values.
When encountering a ?? b
expression, the return value will be:
a
if a
is defined.b
if a
is not defined.For instance, let’s say we have a user
variable, and we want to know if this user has already logged in or not. Firstly, we may use the traditional approach with an if / else
condition like this:
As demonstrated, if the variable user
is not defined, the output will be User not found
.
We can achieve the same outcome more concisely with the ternary operator
As demonstrated, if the variable user
is not defined, the output will be User not found
.
We can achieve the same outcome more concisely with the ternary operator:
Here comes the Nullish Coalescing operator:
While the Nullish Coalescing operator may appear similar to the Logical OR operator (||
), there is a key difference to consider: the ??
operator specifically targets null
and undefined
, while ||
considers all falsy values.
Besides, mixing ??
with those two characters operators &&
and ||
can sometimes lead to unexpected results or errors if we don’t pay attention to operator precedence:
You wouldn’t want to wait in the economy class line if you bought a business class ticket. Similarly, using parentheses to explicitly define the order of operations is a good way to provide clarity and avoid errors: