What is the nullish coalescing operator (??) in JavaScript?
The nullish coalescing operator (??) returns the right-side value when its left-side value is null or undefined, otherwise, it returns the left-side value.
let a = null;
let b = undefined;
let c = 10;
let d = a ?? b ?? c;
console.log(d); // 10
We can rewrite a ?? b as:
(a !== null && a !== undefined) ? a : b;
If the left-side value contains anything other than null or undefined, then ?? returns the left-side value. If the left-side value is 0, NaN, or an null or undefined?? returns the left-side value 0.
Examples
let zero = 0;
console.log( zero ?? 1) ; // 0
let emptyString='';
console.log( emptyString ?? "non-empty") ; // ''
let nan = NaN;
console.log( nan ?? 0) ; // NaN
From the example above, we can see that ?? only returns the right-side value if the left-side value is either null or undefined.
Operator precedence
Since the operator precedence of +,*,/,**, etc.,is higher than??, the ??operator is evaluated after operations like+, *, /and,**`. This is shown below:
let a; let b;
let c = a ?? 10 * b ?? 10;
We wanted to set 10 as the default value of a and b in the above expression if a and b are undefined. However, the above code will first evaluate to 10 * b and then ?? because * has more precedence than ??.
Click here to refer to the operator precedence table.
To avoid the above situation, we should add parentheses to the?? operation. Instead, the above expression should be written as:
let a; let b;
let c = (a ?? 10) * (b ?? 10);
c; // 100
Combine AND/OR with ??
A SyntaxError will be thrown when we combine both the AND (&&) and the OR operators (||) with ?? and without parentheses.
// correct way
let a = (0 || undefined) ?? 10; // 10
// incorrect way
let a = 0 || undefined ?? 10; // this will throw error
Conclusion
- The
??returns the right-side value when its left-side value isnullorundefined, otherwise it returns the left-side value. - The precedence of the
??is lower than some operators, so we should use parentheses when using??in an expression that has operators with precedence higher than that of??. - We can’t use
??with&&and||operators directly. However, by enclosing the??operation inside the parentheses, we can combine??with&&and||operators.