Understand Nullish Coalescing Operator With Examples
Everything You Need To Know About Nullish Coalescing Operator With Examples
2 min read
The Nullish Coalescing operator (??) returns the defined value of the two expressions.
It is recently introduced in ECMAScript 2021.
Let us understand how it works:
The result of a ?? b is: If variable a is undefined or null then the result is b If variable a holds a defined value then the result is 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 ?? operator "" 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 OR operation. 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 valD.
Thank you for reading.