How to use optional chaining in JavaScript
· Category: JavaScript
Short answer
Optional chaining ?. short-circuits and returns undefined if the left-hand side is null or undefined, making nested property access safe and concise.
Steps
- Access nested properties:
javascript const city = user?.address?.city; - Call optional methods:
javascript const result = obj?.getValue?.(); - Combine with nullish coalescing:
javascript const name = user?.name ?? "Anonymous"; - Use with bracket notation:
javascript const key = "id"; const id = user?.[key];
Tips
- Optional chaining only checks
nullorundefined, not other falsy values. - It short-circuits the entire remaining expression.
Common issues
- Overusing optional chaining can hide errors that you actually want to catch.
obj?.foo.barreturnsundefinedifobjis null, but then accessing.baronundefinedthrows if not chained further.