Safe Access
Optional chaining prevents errors when intermediate properties are null or undefined.
It returns undefined instead of throwing a TypeError.
JavaScript Tutorial
Optional chaining lets you safely access nested properties without errors.
It returns undefined if something is missing.
API data is often incomplete. Optional chaining avoids crashes when fields are missing.
It keeps code concise and readable.
obj?.prop
obj?.nested?.prop
obj.method?.()const user = { profile: { name: "Ava" } };
console.log(user?.profile?.name);Safe access to nested properties.
const user = {};
console.log(user?.profile?.name); // undefinedNo error, returns undefined.
Optional chaining prevents errors when intermediate properties are null or undefined.
It returns undefined instead of throwing a TypeError.
Use optional chaining when reading deeply nested data from APIs.
It keeps code short and safe.
Pair optional chaining with nullish coalescing to provide fallbacks.
This is a common pattern in UI code.
Without
let name = "";
if (user && user.profile) {
name = user.profile.name;
}With
const name = user?.profile?.name;Optional chaining works only on declared variables.
If data must exist, validate it explicitly.
Optional chaining returns undefined when it short-circuits.
TypeErrors when accessing missing properties.
No, it returns undefined.
Yes, with method?.() syntax.
Practice: Safely access user.address.city with optional chaining.
const user = {};
// TODO: safely access city
One Possible Solution
const user = {};
const city = user?.address?.city;
console.log(city);Undefined when any part is null or undefined.
Yes, use obj.method?.() syntax.
When a missing value should throw or be validated.
Try different object shapes to see safe access.