Jan 28, 2023

What is a Nullish coalescing operator '??'

Have you ever needed to set a default value in JavaScript, but found that the logical OR (||) returns your default for values like 0 or "" you actually want to keep? That's where the nullish coalescing operator (??) comes in!


What is Nullish Coalescing Operator '??' ?


The nullish coalescing operator returns the right-side value only if the left-side value is null or undefined—not for other "falsy" values like 0, false, or an empty string. It's perfect for safe defaulting without unwanted surprises.

Simple Example

Here, count is 0 (not null/undefined), so the result stays 0.


How Is It Different from ||?


|| returns the right side for any falsy value (null, undefined, 0, '', false, NaN). ?? only checks for null/undefined.


With ??, empty string is kept, with ||, default is used.


Common use cases for the Nullish Coalescing Operator '??'


Common use cases for the nullish coalescing operator (??) in JavaScript include:

1- Setting Default Values for Variables
When a variable may be null or undefined, ?? lets you provide a fallback without overwriting valid falsy values like 0 or "".

2- Handling Optional Function Arguments
Provide defaults only if arguments are missing or undefined.

3- Accessing Configuration or Environment Variables
To safely assign values from config where some might be explicitly set as falsy but valid.

4- Working with API Data or JSON
When API responses might have null or missing properties, use ?? to default them.

5- Combining with Optional Chaining
Used with optional chaining to handle deeply nested properties safely with defaulting.

These use cases make ?? highly valuable in modern JavaScript for robust, readable, and concise default value management.


Conclusion 


Use ?? for precise defaulting—when you want to customize only for truly missing values (null or undefined), but keep the rest just as they are!


EmoticonEmoticon