Nullish Coalescing
The nullish coalescing operator is another upcoming ECMAScript feature that goes hand-in-hand with optional chaining, and which our team has been involved with championing in TC39.
You can think of this feature - the ??
operator - as a way to “fall back” to a default value when dealing with null
or undefined
.When we write code like
let x = foo ?? bar();
this is a new way to say that the value foo
will be used when it’s “present”;but when it’s null
or undefined
, calculate bar()
in its place.
Again, the above code is equivalent to the following.
let x = (foo !== null && foo !== undefined) ?
foo :
bar();
The ??
operator can replace uses of ||
when trying to use a default value.For example, the following code snippet tries to fetch the volume that was last saved in localStorage
(if it ever was);however, it has a bug because it uses ||
.
function initializeAudio() {
let volume = localStorage.volume || 0.5
// ...
}
When localStorage.volume
is set to 0
, the page will set the volume to 0.5
which is unintended.??
avoids some unintended behavior from 0
, NaN
and ""
being treated as falsy values.
We owe a large thanks to community members Wenlu Wang and Titian Cernicova Dragomir for implementing this feature!For more details, check out their pull request and the nullish coalescing proposal repository.