What is Nullish Coalescing in JavaScript
Nullish Coalescing is an operator introduced in JavaScript ES2020. It is represented by two question marks ??
. It is used to provide a default value when the value is null
or undefined
.
Example
const name = null;
const username = name ?? 'Guest';
console.log(username); // Guest
In the above example, the name
variable is null
, so the username
variable will be assigned the value Guest
.
Difference between Nullish Coalescing and Logical OR Operator
The Nullish Coalescing operator ??
is similar to the Logical OR operator ||
, but with a key difference.
The Logical OR operator ||
will return the right-hand side value if the left-hand side value is falsy
: false
, 0
, ' '
, null
, undefined
, NaN
.
const name = '';
const username = name || 'Guest';
console.log(username); // Guest
The Nullish Coalescing operator ??
will return the right-hand side value only if the left-hand side value is null
or undefined
.
const name = '';
const username = name ?? 'Guest';
console.log(username); // ''
Summary
- The Nullish Coalescing operator
??
is a useful operator in JavaScript to provide a default value when the value isnull
orundefined
. - It is similar to the Logical OR operator
||
, but with a key difference. The Nullish Coalescing operator??
will return the right-hand side value only if the left-hand side value isnull
orundefined
.