Nullish coalescing operator '??' Flashcards
As it treats null and undefined similarly, we’ll use a special term here, in this article. We’ll say that an expression is “defined” when it’s neither null nor undefined.
The result of a ?? b is:
if a is defined, then a,
if a isn’t defined, then b.
In other words, ?? returns the first argument if it’s not null/undefined. Otherwise, the second one.
The nullish coalescing operator isn’t anything completely new. It’s just a nice syntax to get the first “defined” value of the two.
For example, here we show user if defined, otherwise Anonymous:
let user;
alert(user ?? “Anonymous”); // Anonymous (user not defined)
another example
let firstName = null; let lastName = null; let nickName = "Supercoder";
// shows the first defined value: alert(firstName ?? lastName ?? nickName ?? "Anonymous"); // Supercoder
Main Difference Between ?? or ||
The important difference between them is that:
|| returns the first truthy value.
?? returns the first defined value.
In other words, || doesn’t distinguish between false, 0, an empty string “” and null/undefined. They are all the same – falsy values. If any of these is the first argument of ||, then we’ll get the second argument as the result.
Another example
In other words, || doesn’t distinguish between false, 0, an empty string “” and null/undefined. They are all the same – falsy values. If any of these is the first argument of ||, then we’ll get the second argument as the result.
In practice though, we may want to use default value only when the variable is null/undefined. That is, when the value is really unknown/not set.
For example, consider this:
let height = 0;
alert(height || 100); // 100
alert(height ?? 100); // 0
Precedence
The precedence of the ?? operator is about the same as ||, just a bit lower. It equals 5 in the MDN table, while || is 6.
That means that, just like ||, the nullish coalescing operator ?? is evaluated before = and ?, but after most other operations, such as +, *.
So if we’d like to choose a value with ?? in an expression with other operators, consider adding parentheses: