Use Nullish Coalescing Operator (??) For Defaults #3
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The nullish coalescing operator (
??
) returns its right side when its left side is nullish (null
orundefined
), and its left side otherwise.For example,
const x = a ?? b
would setx
toa
ifa
has a value, and tob
ifa
isnull
orundefined
.The nullish coalescing operator is very useful to provide default values when a value or an expression is nullish.
Before its introduction in ES2020, this default value pattern was often expressed using the conditional operator.
This refactoring simplifies conditional (ternary) checks to nullish coalescing operator expressions:
a == null ? x : a
becomesa ?? x
a != null ? a : x
becomesa ?? x
a === null || a === undefined ? x : a
becomesa ?? x
a !== null && a !== undefined ? a : x
becomesa ?? x
f(1) != null ? f(1) : x
becomesf(1) ?? x
Learn More: Nullish coalescing operator (MDN)
When two similar-looking function calls have a side effect, this refactoring can change the behavior of the code.
For example, the refactoring changes:
into
If
f(1)
has a side effect, it would have been called one, two or three times before the refactoring, and once after the refactoring.This means that the side effect would have been called a different number of times, potentially changing the behavior.