DEV Community

Cover image for Nullish Coalescing Operator Refactoring

Nullish Coalescing Operator Refactoring

Lars Grammel
Creating automatic refactoring tools for TypeScript and JavaScript. Founder of
・1 min read

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 it was introduced in ES2020, this default value pattern was often expressed using the conditional operator.

You can replace conditional (ternary) checks with nullish coalescing operator expressions:

  • a == null ? x : a becomes a ?? x
  • a != null ? a : x becomes a ?? x
  • a === null || a === undefined ? x : a becomes a ?? x
  • a !== null && a !== undefined ? a : x becomes a ?? x
  • etc.

Learn More: Nullish coalescing operator (MDN)

P42 now supports converting ternaries that provide default values for nullish expressions. The refactoring is available on the playground and for all repositories. Try it out!

Discussion (0)

Forem Open with the Forem app