Codectionary / Developer documentation / JavaScript

JavaScript Optional Chaining & Nullish Coalescing

Optional chaining (?.) stops and produces undefined when its left side is null or undefined. Nullish coalescing (??) supplies a fallback only for null or undefined, not for valid falsey values such as 0 or an empty string.

Syntax

const city = user?.address?.city ?? "Unknown";

Examples

Safely reading nested data

A small, runnable example of this syntax.

const user = { name: "Ada" };
const city = user.address?.city ?? "Unknown";
console.log(city); // Unknown

Best practices

  • Use ?? when 0, false, or an empty string are valid values; use || only when all falsey values should trigger the fallback.
  • Keep examples small while learning, then combine the idea with a real project.

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation