JavaScript ?.

Beginner
5 min read
Updated: Nov 2026
3 examples

Definition and Usage

Optional chaining ?. stops and returns undefined if the value before it is null or undefined, instead of throwing.

JavaScript Syntax

JavaScript
const user = { profile: { city: "London" } };
console.log(user.profile?.city);
console.log(user.address?.city);
Try it Editor

How It Works

  1. Safe path. Missing address does not throw.
  2. Result. undefined when a link is nullish.

Examples

Example 1 — Optional call

fn?.() only calls if fn exists.

JavaScript
const fn = null;
console.log(fn?.(1));
Try it Editor

How It Works

  1. fn is null, so call is skipped.

Example 2 — Optional index

arr?.[0] for maybe-arrays.

JavaScript
const arr = null;
console.log(arr?.[0]);
Try it Editor

How It Works

  1. Nullish base → undefined.

Example 3 — Pair with ??

Default when missing.

JavaScript
const city = undefined?.x ?? "n/a";
console.log(city);
Try it Editor

How It Works

  1. ?. yields undefined.
  2. ?? supplies fallback.

Frequently Asked Questions

Yes. Other falsy values like 0 or "" still continue.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful