JS Optional Chaining
In this page:
Basic Optional Chaining
The optional chaining operator ?. reads a property only if everything before it isn't null or undefined, returning undefined instead of throwing an error when a link in the chain is missing.
Example: Basic Optional Chaining
const user = {};
console.log(user?.name); // undefined, no error
Nested Properties
Optional chaining is especially useful for deeply nested data, like user?.address?.city, where any one of user, address, or city might not exist yet, avoiding a long chain of manual null checks before every property access.
Example: Nested Properties
const user = { address: {} };
console.log(user?.address?.city); // undefined
Optional Method Calls
?. also works before a function call, as in obj.method?.(), so the call is skipped safely if the method doesn't exist, instead of throwing a TypeError — useful for optional callbacks that might not have been provided.
Example: Optional Method Calls
const obj = {};
console.log(obj.greet?.()); // undefined, skipped safely
Optional Array Access
The same operator works with array-style access using ?.[index], letting you safely read an item from an array that might itself be null or undefined, without first checking the array's existence separately.
Example: Optional Array Access
const data = null;
console.log(data?.[0]); // undefined
Optional Chaining Limits
Optional chaining only guards against null and undefined, it does not silently swallow other kinds of errors, so code still needs normal error handling for genuine bugs.
Example: Optional Chaining Limits
const user = null;
try {
console.log(user.name.length); // still throws, unrelated bug
} catch (e) {
console.log("Error:", e.message);
}
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: