Use nullish coalescence in default expression

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

P42 for VS Code
P42 for GitHub
Use nullish coalescence in default expression

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 becomes a ?? x
  • a != null ? a : x becomes a ?? x
  • a !== null && a !== undefined ? a : x becomes a ?? x
  • f(1) != null ? f(1) : x becomes f(1) ?? x
  • if (a != null) { b = a; } else { b = x; } becomes b = 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);


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.

Learn More

Available In