The nullish coalescing operator is the two question marks ??
. It provides a default value.
Syntax:
result = a ?? b
The syntax above means:
- if
a
is defined, thena
; - if
a
isn't defined, thenb
;
The syntax above can be rewritten as shown below:
result = (a !== null && a !== undefined) ? a : b;
See the examples below:
if a
is defined, then a
;
const a = "breakfast"; // a is defined
const b = "lunch";
const result = a ?? b;
console.log(result); // breakfast
if a
isn't defined, then b
;
let a; // a is undefined => const a = undefined;
const b = "lunch";
const result = a ?? b;
console.log(result); // lunch
If you are getting an error, the browser JavaScript engine does not understand the ??
operator.
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.
With parentheses ()
grouping:
let length, width;
const area = (length ?? 100) * (width ?? 50);
console.log(area) // 5000
Without parentheses ()
grouping:
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.
Operators | Precedence |
() | 21 |
** | 16 |
* | 15 |
/ | 15 |
% | 15 |
+ | 14 |
- | 14 |
&& | 7 |
OR | 6 |
?? | 5 |
? | 4 |
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.
Happy Coding!!!
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.