Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Optional Chaining (?.)

Optional chaining (?.) lets you safely access nested properties without crashing when something is null or undefined.

It is especially useful when working with API data, optional config, or dynamic objects.

Why We Need It

Accessing missing properties throws runtime errors, which can break apps and confuse users.

Optional chaining gives you safe, readable access while keeping your code short.

Syntax

object?.property
object?.[expression]
object?.method?.()

Basic Example

1. Basic Optional Chaining

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

console.log(user?.profile?.name); // "Sam"
console.log(user?.profile?.email); // undefined

Missing properties return undefined instead of throwing errors.

Real World Example

2. Optional Method Calls

const logger = {};

logger.log?.("hello"); // no error if log is missing

Optional chaining safely calls a method only if it exists.

Multiple Use Cases

Safe Property Access

Optional chaining prevents errors when accessing nested data that may be missing.

Instead of throwing a TypeError, it returns undefined and lets your code continue safely.

Functions and Arrays

Optional chaining works with function calls and array access too, not just objects.

This is useful for optional callbacks and safely reading list items.

Pairing with ??

Combine optional chaining with nullish coalescing for resilient defaults: `user?.name ?? "Guest"`.

It keeps your code concise and avoids long chains of if-statements.

Avoid Overuse

Optional chaining is not a replacement for validation. If a value must exist, check it explicitly.

Use it when data can legitimately be missing, such as API responses or optional config.

More Examples

3. Optional Array Access

const list = ["a", "b"];

console.log(list?.[0]); // "a"
console.log(list?.[5]); // undefined

Safely access array items even if the array is missing or index is out of bounds.

4. Combine with ??

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

console.log(name);

Pair optional chaining with ?? to supply defaults when data is missing.

Comparison

Without

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

With

const city = user?.profile?.address?.city;

Common Mistakes and Fixes

Using it on undeclared variables

Optional chaining only works on declared variables, not missing identifiers.

Replacing validation with optional chaining

Validate required fields instead of silently ignoring missing values.

Assuming it returns null

Optional chaining returns undefined when it short-circuits.

Overusing in tight loops

Optional chaining is fine, but avoid unnecessary checks in hot paths.

Interview Questions

What problem does optional chaining solve?

It prevents TypeErrors when accessing nested data that may be null or undefined.

What does optional chaining return when it fails?

Undefined.

Can optional chaining call methods?

Yes, with `obj.method?.()` syntax.

Practice Problem

Practice: Safely read a user's email from a nested profile object using optional chaining.

const user = { profile: {} };
// TODO: safely get user.profile.contact.email

One Possible Solution

const user = { profile: {} };
const email = user?.profile?.contact?.email;
console.log(email);

Frequently Asked Questions

What does optional chaining return if it fails?

It returns undefined instead of throwing a TypeError.

Can I use optional chaining on functions?

Yes, you can do `obj.method?.()` to call only if it exists.

Does optional chaining work with arrays?

Yes, use `arr?.[index]` to safely access elements.

When should I avoid optional chaining?

When a value is required. It can hide bugs if you should validate instead.

Try It Yourself

Try optional chaining on different objects and see how undefined is returned safely.