SyntaxStudy
Sign Up
JavaScript Optional Chaining and Nullish Coalescing
JavaScript Beginner 4 min read

Optional Chaining and Nullish Coalescing

?. and ??

?. short-circuits to undefined if the left side is null/undefined. ?? falls back only on null/undefined (not falsy).

Example
const user = null;
user?.address?.city;       // undefined (no error)
user?.getName?.();         // undefined
arr?.[0];                  // undefined if arr is null
const name = user?.name ?? "Guest";  // "Guest"
const count = 0 ?? 10;    // 0 (falsy but not null/undefined)
const empty = "" || "default"; // "default" (|| uses falsy)
Pro Tip

Use ?? instead of || when 0 or "" are valid values that should not trigger the fallback.