Use nullish coalescence in default expression
Replace default value expression with nullish coalescing operator (??
) expressions.

The nullish coalescing operator (??
) returns its right side when its left side is nullish (null
or undefined
), and its left side otherwise.
For example, const x = a ?? b
would set x
to a
if a
has a value, and to b
if a
is null
or undefined
.
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 many types of default value expressions to nullish coalescing operator expressions:
a == null ? x : a
becomesa ?? x
a != null ? a : x
becomesa ?? x
a !== null && a !== undefined ? a : x
becomesa ?? x
f(1) != null ? f(1) : x
becomesf(1) ?? x
if (a != null) { b = a; } else { b = x; }
becomesb = a ?? x;
- etc.
What do I need to consider?
When two similar-looking function calls have a side effect, this refactoring can change the behavior of the code.
For example, the refactoring changes:
let a = f(1) === null || f(1) === undefined ? 'default' : f(1);
into
let a = f(1) ?? 'default';
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.
Configuration
- Code Assist ID (for the configuration file):
use-nullish-coalescence-in-default-expression
- You can configure custom keyboard shortcuts with this code action kind:
refactor.p42.use-nullish-coalescence-in-default-expression
- This code assist provides refactoring suggestions. Learn how to configure the refactoring suggestion visibility.