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 optional chaining operator returns the value of an object property when the object is available and
undefined
otherwise..?
is similar to the standard.
chaining operator, with an added check if the object is defined.The optional chaining operator enables you to write concise and safe chains of connected objects when some of those objects can be
null
orundefined
.Before the introduction of optional chaining in ES2020, the
&&
operator was often used to check if an object is available (obj && obj.value
).This refactoring simplifies existing checks to use the optional chaining pattern:
x && x.a
becomesx?.a
x != null && x.a
becomesx?.a
x !== null && x !== undefined && x.a
becomesx?.a
x && x.a && x.a.b && x.a.b.c && x.a.b.c.d
becomesx?.a?.b?.c?.d
Learn More: Optional Chaining (MDN)
The refactoring replaces falsy checks with nullish checks.
For example, when
a && a.b
is replaced witha?.b
, it changes the execution for certain types, e.g. the empty string""
is falsy but not nullish.However, in many cases these semantic changes will lead actually to more correct behavior.
For example,
text && text.length
will return the empty string, but not its length, whereastext?.length
will return0
for the empty string.Learn more: Truthy (MDN), Falsy (MDN), Nullish (MDN)
This refactoring can affects the number of calls made to methods with side effects.
For example, the refactoring changes:
into
If
f(1)
has a side effect, it would have been called one or two 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.