?? Operator
The ?? (nullish coalescing) operator is a logical operator that returns its right-hand operand if the left-hand operand is null or undefined. Otherwise, it returns the left-hand operand.
Here’s a simple example:
const nullValue = null;
const digit = 0;
const foo = null ?? "default value";
const baz = digit ?? "default digit";
console.log(foo); // default value
console.log(baz); // 0
The main difference between the nullish coalescing operator (??) and the logical OR operator (||) is how they treat falsy values.
The || operator returns the right-hand operand if the left-hand one is falsy (which includes 0, "", NaN, or false).
This can sometimes lead to unexpected results:
const count = 0;
const quantity = count || 42;
console.log(quantity); // 42 instead of 0
The ?? operator solves this issue by only considering null and undefined as invalid.
It’s perfect when you want to use a fallback value only when the first value is missing or undefined:
const count = 0;
const quantity = count ?? 42;
console.log(quantity); // 0
However, unlike ||, you can’t mix ?? directly with && or || without parentheses:
null || undefined ?? "foo"
To fix this, group your expressions with parentheses:
(null || undefined) ?? "foo"
In summary, the ?? operator is a safer alternative to || when working with potential null or undefined values.