The Nullish coalescing operator in useful to handle default values, without short-circuiting on values that result as
Falsy values are
The best example is if you have a property that could assume the values
Additionally, the property should become
true (default value) if it’s not set.
You could be inclined to write something like this:
const trialActive = user.trialActive || true
But what happens if the
user has the property set to
false? The operator
|| will use the right-hand side of the expression, and set the variable
That’s not what we want. Only if the
trialActive property is unset (e.g.
undefined), the value should be assigned to
true, not otherwise.
Here’s where the Nullish coalescing operator comes in handy.
const trialActive = user.trialActive ?? true
In this case, only if the
trialActive property is set to
null, the default value
true is used.
In the other cases, when
user.trialActive contains the value
false, the actual value is used, without short-circuiting the expression.
If you’re interested, here is a blog post that describes Optional chaining in more detail.
For more in-depth explanation, I strongly suggest to skim through this blog post on v8.dev where Nullish coalescing is discussed way more in depth.
Portions of this page are modifications based on work created and shared by the V8 project and used according to terms described in the Creative Commons 3.0 Attribution License.