Skip to content

Optional Chaining

In one line

Optional chaining (?.) safely accesses nested properties, returning undefined instead of throwing when the left side is null or undefined.

In simple words

Optional chaining (?.) is a shorthand for safe property access. If the left side is null or undefined, it short-circuits and returns undefined instead of throwing a TypeError. This avoids the need for explicit null checks.

For example, user?.address?.city returns undefined if user is null or if user.address is null, instead of throwing. Without optional chaining, you'd need user && user.address && user.address.city.

Optional chaining also works with method calls (obj?.method()) and bracket access (arr?.[0]). It is available in TypeScript 3.7+ and is now standard JavaScript (ES2020).

Example

typescript
interface User { profile?: { name?: string; }; }
const user: User = {};

// Without optional chaining
const name1 = user && user.profile && user.profile.name; // undefined

// With optional chaining
const name2 = user?.profile?.name; // undefined (much cleaner)

Optional chaining short-circuits to undefined instead of throwing on null/undefined.

Related terms

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