ES11 — Nullish Coalescing Operator
Nullish Coalescing operator is a new feature in ES2020. It’s symbol is ?? i.e. double question mark.
It is a logical operator applies 2 operands, returns its value of :
1. Right hand operand value when LHS operand is null or undefined.
2. Right hand operand value when RHS operand is not null or undefined.
This will be useful for default to fallback value when object properties are null or undefined.
Syntax:
Left Operand ?? Right Operand
Let’s take an example to understand better about this operator:
Difference between Logic OR Operator vs Nullish Coalescing Operator:-
?? considered nullish value i.e. null or undefined, But not boolean values. whereas || considered falsey values i.e. null or undefined or NaN , or “ ” or 0.
Let’s take an example :-
let result = value ?? 0;
console.log(result)
If the value is one of null, undefined value then the default value is 0(zero)
let result = value || 0;
console.log(result)
If the value is one of null, undefined, empty string i.e. “ ” , 0 , NaN value then the default value is 0 (zero).