Reading a property from undefined or null throws an error. This is one of the most common JavaScript errors.
const user = { name: "Maya" };
console.log(user.address.city); // error on purpose: address is undefined
You get Cannot read properties of undefined (reading 'city'). Optional chaining solves it: put ?. where something might be missing. If the left side is null or undefined, JavaScript stops and the whole expression becomes undefined.
const user = { name: "Maya" };
console.log(user.address?.city); // → undefined
const other = { address: { city: "Pune" } };
console.log(other.address?.city); // → Pune
Three forms
const user = {
name: "Maya",
tags: ["admin"],
greet() { return "Hi, " + this.name; }
};
console.log(user.profile?.email); // → undefined (property)
console.log(user.tags?.[0]); // → admin (array or bracket access)
console.log(user.greet?.()); // → Hi, Maya (method call)
console.log(user.logout?.()); // → undefined (method does not exist)
Combine it with ??
const settings = {};
const theme = settings.display?.theme ?? "light";
console.log(theme); // → light
Do not overuse it
?. hides problems. If a value should always exist, a clear error is better than a silent undefined. Use it for data that is truly optional, such as API fields or user settings.
// Too forgiving: if config is missing, you will not notice
config?.server?.port?.toString()
Also, ?. only checks the part right before it. user?.address.city still throws if user exists but has no address.