Beginner LevelJavaScript & TypeScript
What is the optional chaining operator (?.) and how does it prevent errors?
❓ Interview Prompt: Explain optional chaining syntax for property access, method calls, and dynamic key indexing.
The optional chaining operator (?.) reads nested object properties without throwing a TypeError if an intermediate reference is null or undefined.
Behavior:
If the object before ?. is null or undefined, evaluation short-circuits and returns undefined immediately instead of throwing an error.
Three Forms:
1
Property access:
obj?.prop2
Bracket notation:
obj?.[key]3
Function/method call:
obj.method?.()Code Implementation Example
javascript
const user = {
profile: {
name: 'Alice',
getAddress: () => ({ city: 'Paris' })
}
};
// Without optional chaining (verbose guard checks)
const cityOld = user && user.profile && user.profile.address && user.profile.address.city;
// With optional chaining (clean & safe)
const city = user?.profile?.address?.city; // undefined (no error thrown!)
// Optional method execution
const currentCity = user?.profile?.getAddress?.()?.city; // "Paris"
const unknownMethod = user?.profile?.nonExistentMethod?.(); // undefined (no call attempt)💡Nested property access and conditional method calls using optional chaining.
🎯 Interview Key Takeaway
Use ?. to safely access deeply nested properties and call optional methods without runtime TypeError crashes.
#Optional Chaining#Safety#ES2020#Beginner
Back to all JavaScript & TypeScript Questions→