|$ curl https://forge-ai.dev/api/markdown?path=docs/js/optional-chaining
$cat docs/optional-chaining-&-nullish-coalescing.md
updated Recently·14 min read·published

Optional Chaining & Nullish Coalescing

JavaScriptBeginner
Introduction

Optional chaining (?.) and nullish coalescing (??) are ES2020 features that simplify safe property access and default value assignment. They handle null and undefined without the verbosity of manual checks or logical OR operators.

Optional Chaining (?.)

Safely access nested properties without throwing on intermediate null or undefined.

optional-chaining.js
JavaScript
1const user = {
2 profile: {
3 address: {
4 city: "New York",
5 },
6 },
7};
8
9// Without optional chaining
10const city = user && user.profile && user.profile.address
11 ? user.profile.address.city
12 : undefined;
13
14// With optional chaining — short-circuits to undefined
15const city2 = user?.profile?.address?.city;
16// "New York"
17
18// Works with dynamic access and function calls
19const nested = data?.items?.[0]?.name;
20const result = obj?.method?.();
21
22// Optional chaining on the left side of assignment
23let name = null;
24name ??= "default"; // assigns "default" only if name is null/undefined
Nullish Coalescing (??)

Returns the right-hand operand only when the left-hand operand is null or undefined. Unlike ||, it does not treat 0, "", or false as falsy.

nullish-coalescing.js
JavaScript
1const value = 0;
2const orResult = value || 42; // 42 (0 is falsy)
3const nullishResult = value ?? 42; // 0 (0 is not null/undefined)
4
5const empty = "";
6const orEmpty = empty || "fallback"; // "fallback"
7const nullishEmpty = empty ?? "fallback"; // ""
8
9const isActive = false;
10const orBool = isActive || true; // true
11const nullishBool = isActive ?? true; // false
12
13// Logical nullish assignment (ES2021)
14config.timeout ??= 5000; // only assigns if timeout is null/undefined
15user.name ??= "Anonymous";

info

Use ?? for default values when valid data includes 0, "", or false. Use || only when you want to treat all falsy values as absent.
Combined Pattern

Optional chaining and nullish coalescing work together for clean, safe access with defaults.

combined-pattern.js
JavaScript
1function getDisplayName(user) {
2 return user?.profile?.displayName ?? user?.username ?? "Anonymous";
3}
4
5function getConfigValue(config, path) {
6 return path.split(".").reduce(
7 (obj, key) => obj?.[key], config
8 ) ?? "default";
9}
10
11// Safe array access with default
12const firstItem = arr?.[0] ?? "empty";
13
14// Safe function call
15const handler = handlers?.[type] ?? defaultHandler;
16handler?.(event);