The nullish coalescing operator (??
) is a logical operator that allows providing a default value when an expression is null
or undefined
.
This operator, introduced in ECMAScript 2020 (ES11), provides a more precise and clear way to handle null and undefined values (compared to other traditional approaches like using ||
).
The nullish coalescing operator is very useful for simplifying and improving the readability of code when working with values that contain null
or undefined
.
Coalescence is a term that refers to the process of joining or merging two or more elements into one.
Syntax of the nullish coalescing operator
The syntax of the nullish coalescing operator is simple:
let result = value1 ?? value2;
In this case,
- If
value1
is notnull
orundefined
,result
will take the value ofvalue1
. - If
value1
isnull
orundefined
,result
will take the value ofvalue2
.
For example, in this case
let username = user.name ?? 'No idea, mate';
console.log(username); // 'No idea, mate'
Here,
- If the username were
Pedro
,username
would bePedro
. - Therefore,
username
takes the value ‘No idea, mate’.
Combination with other operators
The ??
operator fits wonderfully well (❤️) with other operators like the optional chaining operator ?.
.
let username = user?.name ?? 'Unknown';
console.log(username); // 'Unknown'
In this case, username
will be ‘No idea, mate’ if either,
user
isnull
user
is notnull
, but its propertyname
isnull
In the previous example, without ?.
, if user
had been null
, it would have thrown an exception.
Comparison with other methods of handling null values
Traditional Conditionals
In earlier versions of JavaScript, handling null and undefined values was done using conditionals (||
).
let name = value || 'User';
This is quite worse, as ||
considers any falsy value (like 0
, false
, ''
, etc) as a reason to use the default value.
Therefore, it doesn’t really respond to undefined
or null
, but to a bunch of things!
Avoid using ||
. It’s much more modern and “better” to use ??
, that’s what it’s for 😉
Ternary Operator
The ternary operator is another alternative for handling null values. Although it is less elegant and can result in harder-to-read code:
let name = (value !== null && value !== undefined) ? value : 'User';
The ??
operator provides a more concise and clear way to handle null and undefined values.
Don’t do that, and use ??
for goodness’ sake! 😉