Use Nullish Coalescing Operator (??) For Defaults

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.

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:

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.

Original Code

Changes

1a = "123";1a = "123";
2b = a != null ? a : "456";2b = a ?? "456";
3c = a === undefined || a === null ? "789" : a;3c = a ?? "789";
4 4
5if (a != null) {5d = a ?? "xyz";
6 d = a;
7} else {
8 d = "xyz";
9}
11a = "123";
2b = a != null ? a : "456";
3c = a === undefined || a === null ? "789" : a;
2b = a ?? "456";
3c = a ?? "789";
44
5if (a != null) {
6 d = a;
7} else {
8 d = "xyz";
9}
5d = a ?? "xyz";

Transformed Code

a = "123";
b = a ?? "456";
c = a ?? "789";

d = a ?? "xyz";

Explore More