Nullish Coalescing Operator
The nullish coalescing operator is a stage 3 proposal which means it is very likely going to become a part of the JavaScript language so it’s a good idea to understand what it is and what it does.
When accessing a property, it is sometimes necessary to set a default value, and this is usually done using the ||
operator, like this:
const value = obj.value || 'default value';
But there is an issue with this code. The variable value
will equal 'default value'
not only when value
is null
or undefined
, but also any time it is falsy:
console.log(null || 'default value'); // default value
console.log(undefined || 'default value'); // default value
console.log(false || 'default value'); // default value
console.log(0 || 'default value'); // default value
console.log('' || 'default value'); // default value
console.log(NaN || 'default value'); // default value
While that is probably the intended behavior when a variable is null
or undefined
, it’s not super clear whether that’s what is desirable when the variable is equal to 0
or ''
.
This is where the nullish coalescing operator ??
comes in play. Instead of defaulting falsy values, the nullish coalescing operator defaults only null
and undefined
:
console.log(null ?? 'default value'); // default value
console.log(undefined ?? 'default value'); // default value
console.log(false ?? 'default value'); // false
console.log(0 ?? 'default value'); // 0
console.log('' ?? 'default value'); // ''
console.log(NaN ?? 'default value'); // NaN
This becomes particularly useful with the Optional Chaining operator I wrote about previously.
It is now possible to write this:
const value = nested?.first ?? 'no value';
Which means the variable value
will be defaulted to 'no value'
only if the property first
is null
or undefined
.
To enable the nullish coalescing operator in a create-react-app
, just check out this code or follow this article and run the following command:
$ yarn add @babel/plugin-proposal-nullish-coalescing-operator -D
And modify the .babelrc
file so it looks like this:
{
"plugins": [
"@babel/plugin-proposal-optional-chaining",
"@babel/plugin-proposal-nullish-coalescing-operator"
]
}
That’s it!