Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Optional Chaining with Objects

Optional chaining lets you safely access nested properties without errors.

It returns undefined if something is missing.

Why We Need It

API data is often incomplete. Optional chaining avoids crashes when fields are missing.

It keeps code concise and readable.

Syntax

obj?.prop
obj?.nested?.prop
obj.method?.()

Basic Example

1. Basic usage

const user = { profile: { name: "Ava" } };

console.log(user?.profile?.name);

Safe access to nested properties.

Real World Example

2. Missing data

const user = {};
console.log(user?.profile?.name); // undefined

No error, returns undefined.

Multiple Use Cases

Safe Access

Optional chaining prevents errors when intermediate properties are null or undefined.

It returns undefined instead of throwing a TypeError.

Nested Objects

Use optional chaining when reading deeply nested data from APIs.

It keeps code short and safe.

Combine with Defaults

Pair optional chaining with nullish coalescing to provide fallbacks.

This is a common pattern in UI code.

More Examples

3. With fallback

const user = {};
const name = user?.profile?.name ?? "Guest";

console.log(name);

Provide a default with ?? .

4. Optional method

const user = { getName: null };
const name = user.getName?.();

console.log(name);

Safe method call if it exists.

Comparison

Without

let name = "";
if (user && user.profile) {
  name = user.profile.name;
}

With

const name = user?.profile?.name;

Common Mistakes and Fixes

Using on undeclared variables

Optional chaining works only on declared variables.

Skipping required validation

If data must exist, validate it explicitly.

Assuming null result

Optional chaining returns undefined when it short-circuits.

Interview Questions

What does optional chaining prevent?

TypeErrors when accessing missing properties.

Does it return null?

No, it returns undefined.

Can you use it on functions?

Yes, with method?.() syntax.

Practice Problem

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);

Frequently Asked Questions

What does optional chaining return?

Undefined when any part is null or undefined.

Can I use it with methods?

Yes, use obj.method?.() syntax.

When should I avoid it?

When a missing value should throw or be validated.

Try It Yourself

Try different object shapes to see safe access.