Skip to content

JavaScript Tutorial Operators

JavaScript Optional Chaining (?.)

Lesson 26 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

Reading a property from undefined or null throws an error. This is one of the most common JavaScript errors.

script.js
JS
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.

script.js
JS
const user = { name: "Maya" };
console.log(user.address?.city); // → undefined

const other = { address: { city: "Pune" } };
console.log(other.address?.city); // → Pune

Three forms

script.js
JS
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 ??

script.js
JS
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.

script.js
JS
// 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.

info
Support
Optional chaining is part of the language since ES2020 and works in all current browsers.