Sitemap
Press enter or click to view image in full size

The Nullish coalescing operator (??)

2 min readApr 9, 2023

--

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.

Get Ahmad Joya’s stories in your inbox

Join Medium for free to get updates from this writer.

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:

Logical Operator OR ||

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:

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:

Nullish Coalescing Operator

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

--

--