The nullish coalescing operator is the two question marks
??. It provides a default value.
result = a ?? b
The syntax above means:
ais defined, then
aisn't defined, then
The syntax above can be rewritten as shown below:
result = (a !== null && a !== undefined) ? a : b;
See the examples below:
a is defined, then
const a = "breakfast"; // a is defined const b = "lunch"; const result = a ?? b; console.log(result); // breakfast
a isn't defined, then
let a; // a is undefined => const a = undefined; const b = "lunch"; const result = a ?? b; console.log(result); // lunch
SyntaxError: Unexpected token '?'
In such a case, you need to upgrade the browser.
Nullish operator with other Operators
For a nullish operator used with other operators, it's advisable to use parentheses to specify the order of operations.
let length, width; const area = (length ?? 100) * (width ?? 50); console.log(area) // 5000
let length, width; const area = length ?? 100 * width ?? 50; console.log(area) // NaN
Nullish operator with Logical Operators
const x = (5 && 10) ?? 15; // (5 && 10) = 10 => 10 ?? 15 console.log(x); // 10
Nullish Operator Precedence Nullish operator has the least precedence as compared to other logical operators.
Check out the full list of operators precedence at MDN.
The highest operator precedence is
() in any math operation. It specifies the order of operations.
TechStack | Bluehost
- Get a website with a free domain name for 1st year and a free SSL certificate.
- 1-click WordPress install and 24/7 support.
- Starting at $3.95/month.