The nullish coalescing operator (??) provides a better way to handle default values when dealing with null or undefined.
Basic Syntax
Why Use Nullish Coalescing
With Optional Chaining
Function Parameters
Object Defaults
Nullish Coalescing Assignment
Chaining
With Logical Operators
Type Coercion
Common Use Cases
TypeScript Integration
Comparison Summary
Best Practices
When to Use ??:
✓ Default values for optional config
✓ API response fallbacks
✓ User input defaults
✓ When 0, '', or false are valid
When to Use ||:
✓ When any falsy value means "use default"
✓ Boolean coercion is desired
✓ Legacy code compatibility
With Optional Chaining:
✓ Use both together: obj?.prop ?? default
✓ Chain from access to default naturally
✓ Handles deep nesting elegantly
Avoid:
✗ Mixing ?? with && or || without ()
✗ Using || when ?? is needed
✗ Forgetting null vs undefined semantics
Conclusion
The nullish coalescing operator (??) provides precise control over default values by only triggering for null and undefined, unlike || which triggers for any falsy value. Use it when zero, empty strings, or false are valid values. Combine it with optional chaining (?.) for elegant handling of potentially missing nested properties. The ??= assignment operator adds convenient lazy initialization patterns.