The nullish coalescing operator (??
) is a new feature of JavaScript. It provides a more intuitive way to handle null
and undefined
values.
It returns its right-side value when its left-side value is null
or undefined
, otherwise, it returns the left-side value.
const a = null ?? "default value";
const b = undefined ?? "default value";
console.log(a); // "default value"
console.log(b); // "default value"
The nullish coalescing (??) is a specific case of logical OR ( | | ) operator. The logical OR operator returns its right-side value when its left-side value is any falsy value, not just null
or undefined
.
Why would I use the nullish, when I could use OR ?
We could use the traditional OR operator(||) to assign a default value to a variable, but there are some cases, where OR (||) may not behave as you expect.
For example, 0
and ""
are falsy values. We may want to consider them as valid values in some cases.
In the below example, OR (||) would return the right-side value, when the left-sided value is 0
or ""
. But, we expect OR to return the right-sided value only when the left-sided value is null
or undefined
, not when the left-sided value is 0
or ""
.
const count = 0;
const text = "";
const qty = count || 10;
const message = text || "hi!";
console.log(qty); // 10 and not 0
console.log(message); // "hi!" and not ""
To overcome this pitfall, We could use the nullish operator ??
. Because it returns the right-sided value only when the left-sided value is null
or undefined
.
Let's write the above example with the nullish operator ??
.
const count = 0;
const text = "";
const qty = count ?? 10;
const message = text ?? "hi!";
console.log(qty); // 0
console.log(message); // ""