Optional Chaining
Optional Chaining (?.)
Section titled “Optional Chaining (?.)”Introduction
Section titled “Introduction”Optional chaining ?. allows you to safely access deeply nested object properties without throwing an error if an intermediate property is null or undefined.
Why Do We Need This?
Section titled “Why Do We Need This?”Before optional chaining, accessing nested properties required verbose checks:
// Beforeconst city = user && user.address && user.address.city;
// Afterconst city = user?.address?.city;Visual Explanation
Section titled “Visual Explanation”flowchart TD A["user?.address?.city"] B{"user exists?"} C{"address exists?"} D["Return city"] E["Return undefined"]
A --> B B -->|Yes| C B -->|No| E C -->|Yes| D C -->|No| EExamples
Section titled “Examples”const user = { name: 'Alice', address: null};
user?.name; // 'Alice'user?.address?.city; // undefined — no error!user?.profile?.age; // undefined — no error!Method Calls
Section titled “Method Calls”const obj = { greet: () => 'Hello'};
obj.greet?.(); // 'Hello'obj.farewell?.(); // undefined — no errorSummary
Section titled “Summary”?.safely accesses nested properties- Returns
undefinedif intermediate value isnull/undefined - Also works with method calls:
obj.method?.() - Prevents “Cannot read property of undefined” errors