With the presentation of Symbols (fortunately to which you can make 100% interesting properties - consistently), Optional Chaining, Nullish Coalescing, destructuring assignment and much more JavaScript is turning into a truly steady language reasonable for enormous codebases and the advancement incredible applications.
The ??
operator is a logical operator that returns its right-hand side operand if its left-hand side operand is null or undefined, else it returns its left-hand side operand.
cons a = null,
b = undefined,
c = '',
d = 0;
a ?? 'default' // => 'default'
b ?? 'default' // => 'default'
c ?? 'default' // => ''
d ?? 'default' // => 00
c || 'default' // => 'default'
d || 'default' // => 'default'
In practice, it is mainly used for assigning a default value to a variable. You might know that up to now this was done using the ||
operator, like this:
const bus = bms || 'default'
// if bms is falsy value, bus is given the value 'default'. Falsy are 0 and '' too.
But what if you want to exclude not all falsy values, but only null and undefined? Then you use ??
operator.
||
vs ??
cons a = null,
b = undefined,
c = '',
d = 0,
e = 'any truthy value';
a ?? 'default' // => 'default'
b ?? 'default' // => 'default'
c ?? 'default' // => ''
d ?? 'default' // => 0
e ?? 'default' // => 'any truthy value'
a || 'default' // => 'default'
b || 'default' // => 'default'
c || 'default' // => 'default'
d || 'default' // => 'default'
e || 'default' // => 'any truthy value'
You can't chain directly the ??
operator with logical OR (||)
or logical AND &&
and if you do so it throws a SyntaxError. However, you can use parenthesis to separate them.
null || undefined ?? 'default' // SyntaxError
true || undefined ?? 'default' // SyntaxError
(true || undefined)?? 'default' // True
The nullish coalescing operator ??
also has a relation with the optional chaining operator (covering in the next post). This is the best JavaScript feature you should know.
Thanks for Reading😀