Back to Blog
JavaScriptNullish CoalescingES2020Operators

JavaScript Nullish Coalescing Guide

Master the nullish coalescing operator for handling null and undefined values.

B
Bootspring Team
Engineering
August 24, 2018
8 min read

The nullish coalescing operator (??) provides a better way to handle default values when dealing with null or undefined.

Basic Syntax

Loading code block...

Why Use Nullish Coalescing

Loading code block...

With Optional Chaining

Loading code block...

Function Parameters

Loading code block...

Object Defaults

Loading code block...

Nullish Coalescing Assignment

Loading code block...

Chaining

Loading code block...

With Logical Operators

Loading code block...

Type Coercion

Loading code block...

Common Use Cases

Loading code block...

TypeScript Integration

Loading code block...

Comparison Summary

Loading code block...

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.

Share this article

Help spread the word about Bootspring

Related articles