Optional chaining (?.) safely accesses nested properties without explicit null checks. Here's how to use it.
Basic Syntax#
Property Access#
Method Calls#
With Nullish Coalescing#
Short-Circuiting#
Common Patterns#
Array Methods#
With Delete#
TypeScript Integration#
Best Practices#
Usage:
✓ Use for potentially missing properties
✓ Combine with ?? for defaults
✓ Use in API response handling
✓ Safe event handler access
Patterns:
✓ Chain multiple levels safely
✓ Use with array access
✓ Safe method calls
✓ Configuration access
Readability:
✓ Don't overuse on known objects
✓ Consider extracting complex chains
✓ Document expected structures
✓ Use TypeScript for clarity
Avoid:
✗ Using when value is required
✗ Excessive chaining (code smell)
✗ Hiding bugs in data structure
✗ Using || instead of ??
Conclusion#
Optional chaining simplifies safe property access and eliminates verbose null checks. Combine with nullish coalescing (??) for default values. Use it for API responses, configuration objects, and any situation where properties may be undefined. Remember that it short-circuits evaluation when encountering null or undefined.