DEV Community

Cover image for Nullish Coalescing Operator Refactoring
Lars Grammel for P42

Posted on • Updated on • Originally published at p42.ai

Nullish Coalescing Operator Refactoring

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. Try it out in the P42 VS Code Extension!

Discussion (0)