JS: Null-Coalescing Operator: Modern JavaScript allows ?? for null & undefined | JavaScript
JavaScript ?? Null-Coalescing Operator
In modern versions of JavaScript, Null-Coalescing Operator ??
results the next operand if the previous operand is either null
or undefined
.??
overcomes the backdraws of ||
in older versions of JavaScript to achieve ??
functionality.??
takes two arguments and can be nested.
var x = null;
var y = 3;
var z = x ?? y;
console.log(z);
3
??
reulsts 2nd (alternate) operand y because the first operand null
.
var x;
var y = 'y-value';
var z = x ?? y;
console.log(z);
y-value
multiple expressions can be given in a single statement for ??
operator. the first non-null
or non-undefined
value is considered.
var x = null;
var y = undefined;
var z = x ?? y ?? 'other-value';
console.log(z);
other-value
Since x and y are null
and undefined
, respectively, so 'other-value'
is assigned to z.
falsy other than null
& undefined
falsy statement other than null
& undefined
are considered i.e. 0
, false
and ''
etc.
var x = 0;
var y = undefined;
var z = x ?? y;
console.log(z);
0
var x = false;
var y = null;
var z = x ?? y;
console.log(z);
false
var x = ''; //Empty string
var y = null;
var z = x ?? y;
console.log(z);
var x = NaN; //Not a Number
var y = null;
var z = x ?? y;
console.log(z);
NaN
??
alternate in older versions of JavaScript
Null-Coalescing Operator (??
) is not available in older versions of JavaScript. This functionality can be achieved with ||
upto some extent with some drawbacks.
var x = null;
var y = 3;
var z = x || y;
Demerits of Null-Coalescing using ||
In JavaScript, ||
acts as OR operator, since ||
is a conditional operator and returns the next operand (value) when first fails.
In case, if the first operand is falsy i.e. (zero 0
, empty string ''
, false
, null
, undefined
etc.), instead of returning first operand (value) returns the second.
Please have a look at falsy chapter of this JavaScript tutorial.
If the code expect other falsy values, then replacing the following line may work as required.
var z = x == null ? y : x;
Summary
- JavaScript
||
may work as??
of C# for with some limitations - Falsy expressions may cause buggy code, need for write code carefully