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
How Is It Different from ||?
|| returns the right side for any falsy value (null, undefined, 0, '', false, NaN). ?? only checks for null/undefined.
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 "".
Provide defaults only if arguments are missing or undefined.
To safely assign values from config where some might be explicitly set as falsy but valid.
When API responses might have null or missing properties, use ?? to default them.
Used with optional chaining to handle deeply nested properties safely with defaulting.
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!