Use Optional Chaining
Replace chains of nullish checks with the optional chaining operator (
The optional chaining operator returns the value of an object property when the object is available and
.? 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
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.abecomes
x != null && x.abecomes
x !== null && x !== undefined && x.abecomes
x && x.a && x.a.b && x.a.b.c && x.a.b.c.dbecomes
Code Action Safety
The refactoring replaces falsy checks with nullish checks.
For example, when
a && a.b is replaced with
a?.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.
text && text.length will return the empty string, but not its length, whereas
text?.length will return
0 for the empty string.
This refactoring can affects the number of calls made to methods with side effects.
For example, the refactoring changes:
let a = x() != null && x().a;
let a = x()?.a;
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.