DEV Community

Cover image for Nullish Coalescing Operator Refactoring
Lars Grammel for P42

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

3

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!

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay