Skip to content

Optional Chaining

In one line

Optional chaining (?.) accesses a property only if the left side is not null or undefined, otherwise returns undefined.

In simple words

Optional chaining (?.) lets you safely access deeply nested properties without a long chain of if checks. If the left side of ?. is null or undefined, the whole expression short-circuits and returns undefined instead of throwing a TypeError.

Before optional chaining, accessing user.address.city required checking user && user.address && user.address.city. With optional chaining, you write user?.address?.city — if any link is nullish, the result is undefined. This is shorter, clearer, and less error-prone.

Optional chaining works for properties (obj?.prop), method calls (obj?.method()), and function calls (func?.()). It also has a bracket form (obj?.[key]). It was added in ES2020 and is one of the most loved modern JavaScript features.

Example

javascript
const user = { name: "Ada", address: { city: "London" } };

console.log(user?.address?.city);    // "London"
console.log(user?.contact?.phone);   // undefined (no throw)

// Without optional chaining this throws:
// console.log(user.contact.phone); // TypeError

const arr = null;
console.log(arr?.length); // undefined

?. short-circuits to undefined when the left side is null/undefined, instead of throwing. The whole chain stops at the first nullish link.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary