Just last week TC39 (the committee behind ECMAScript) greenlit a few new awesome features. This week we'll dive into nullish coalescing. Sort of a mouthful of a name, isn't it?
Let's break it down.
Often in programming, we can't count on a value existing, and we want to set a default instead. There are a few different ways to do this, but one of the most common is to use or, represented by
let snippet = null let snippet = snippet || "code snippet"
In this example,
snippet is set to
null. Since we always want a string, we'll reassign it using the or operator. This expression will keep
snippet the same unless
undefined, but they also include
false, and empty string. Yikes! That means that this expression will evaluate a little differently than we might want it to.
let age = 0 let age = age || 1
In this example,
0 is a valid age! We don't want that. We only want to default to
age is not a number.
Note that there is a function
isNaNto check this, but we're ignoring that situation for now.
We quickly discover that there are plenty of other situations this causes problems in. My particularly favorite is the empty string case. Oftentimes you don't want a
null string variable because it will throw errors when you attempt to manipulate it. But having an empty string is ok.
let message = "" let message = message || "Welcome to DEV"
message gets set to "Welcome to DEV" even when we don't want it to.
Note that we can check for type of
stringValue, but that's annoying.
And that's what this addition is all about. We can replace our
|| check with the nullish coalescing operator,
??. Using this operator works much the same as
||, with one major exception. If the value on the left-hand side of the operator is
undefined the default (right-hand side) will be used. Otherwise, the default is ignored.
So let's look at our three examples.
let snippet = null let snippet = snippet ?? "code snippet"
This will still resolve to
How about in the case of a falsy value like zero?
let age = 0 let age = age ?? 1
age is still
0 is not
undefined, so the right-hand argument to the operator is ignored.
And finally our empty string example.
let message = "" let message = message ?? "Welcome to DEV"
message stays an empty string, just like we want.
Isn't it?! Falsy values have caused me lots of strife over the years when they caused unintentional side effects, so I'm super psyched for this. Stay tuned for other new features. We'll tackle optional chaining next.