DEV Community

Cover image for The Nullish coalescing operator (??)
Ahmad Joya
Ahmad Joya

Posted on

The Nullish coalescing operator (??)

The Nullish coalescing operator (??) is a new operator introduced in ECMAScript 2020 (also known as ES11). It is used to provide a default value when a variable is null or undefined.

In JavaScript, when you want to set a default value for a variable that could be null or undefined, you often use the logical OR (||) operator. For example:
Image description

However, this approach has a limitation: if the variable is falsy, but not null or undefined (e.g., it could be an empty string or the number 0), the default value will still be assigned. For example:
Image description

To solve this problem, the Nullish coalescing operator (??) was introduced. It only checks for null or undefined values, and ignores other falsy values. For example:
Image description

In this way, the Nullish coalescing operator allows you to more accurately and safely provide default values for variables that may be null or undefined

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