Nullish coalescing operator ??
A Simple Guide to understanding the basics (with examples)
The Nullish Coalescing operator (??) returns the defined value of the two expressions
The result of
a ?? b is:
ais undefined or null then b
aholds a defined value then a
Remember: 0 is evaluated as falsy but ?? specifically looks for undefined or null only.
leftExpression ?? rightExpression
The right-hand expression is returned only if the left-hand expression is null or undefined
const val = null ?? "Some value"; console.log(val); // Output: "Some value"
In the above example, "Some value" is assigned to
val because the left-hand expression evaluates to null.
const val = 0 ?? 30; console.log(val); // Output: 0
Since 0 is neither null nor undefined, hence
val is assigned 0 instead of 30.
Nullish coalescing (??) seems quite similar to the || (OR) operator, isn't it?
Well, the answer is No. Let's see how!
Comparison with logical || (OR) operator
const valA = "" ?? "default for A"; console.log(valA); // Output: "" const valB = "" || "default for A"; console.log(valB); // Output: "default for A"
In the first
console.log() statement empty(
"") string is returned because the
"" doesn't evaluate to null or undefined.
In the second statement
"default for A" is returned because the || operator treats
"" as false and hence does a logical
false || "default for A" evaluates to "default for A"
const valC = 0 ?? 20; console.log(valC); // Output: 0 const valD = 0 || 20; console.log(valD); // Output: 20
Similarly, in the first statement since 0 is neither null nor undefined
valA is assigned to 0 (left-hand expression).
However, in the second statement 0 evaluates to false, and
false || 20 results in 20 being assigned to