Optional chaining (?.) provides a safe way to access nested object properties without checking each level.
Basic Syntax#
Property Access#
Method Calls#
Array Access#
With Nullish Coalescing#
Function Parameters#
Object Methods#
Delete Operator#
Short-Circuiting#
Class Properties#
API Response Handling#
Event Handling#
Common Patterns#
When NOT to Use#
TypeScript Integration#
Best Practices#
Use Optional Chaining When:
✓ Property might not exist
✓ Object might be null/undefined
✓ Accessing API response data
✓ Working with optional config
Combine With:
✓ Nullish coalescing (??) for defaults
✓ Try-catch for actual errors
✓ Type guards for type narrowing
Avoid:
✗ Hiding genuine errors
✗ Overusing on required properties
✗ Using || instead of ?? for defaults
✗ Excessive chaining depth
Performance:
✓ No significant overhead
✓ Short-circuits efficiently
✓ Same as manual null checks
Conclusion#
Optional chaining (?.) simplifies safe property access and eliminates verbose null checks. Use it with nullish coalescing (??) for default values, but don't overuse it to hide errors or on properties that should always exist. It's perfect for API responses, configuration objects, and any data where properties might be missing.