Tutorials JavaScript Optional Chaining & Nullish
Ch 52 / 78
Chapter 52 Intermediate 6 min read JavaScript

Optional Chaining & Nullish Coalescing

Two of the most practical ES2020 additions to JavaScript — ?. (Optional Chaining) lets you safely access deeply nested properties without throwing TypeError, while ?? (Nullish Coalescing) provides a clean, precise fallback that only triggers for null and undefined — not for falsy values like 0 or "". Together they eliminate entire categories of defensive boilerplate code.

What you'll learn
Optional chaining ?. for safe property access
Optional method calls and array element access
Nullish coalescing ?? — fallback for null/undefined only
?? vs || — the critical difference
Nullish assignment ??=, ||=, &&=
Combining ?. and ?? for real-world API data

Overview — Two Problems, Two Operators

Before ES2020, accessing a nested property on a potentially null or undefined object required tedious guard chains. And providing fallback values with || incorrectly rejected valid falsy values like 0 and "". These two operators solve both problems elegantly.

Optional Chaining ?.
Short-circuits to undefined instead of throwing a TypeError when a property doesn't exist.
Nullish Coalescing ??
Returns the right-hand side only when the left side is null or undefined — ignores 0, "", false.
Logical Assignment ??=
Assigns a value only if the variable is currently null or undefined. Also: ||= and &&=.
Combined Power
Chain ?. with ?? to safely traverse API data and provide meaningful defaults in one expression.
Operator Name Example Result
?. Optional chaining user?.address?.city undefined
?.() Optional method call obj.fn?.() undefined
?.[] Optional indexing arr?.[0] undefined
?? Nullish coalescing null ?? "default" "default"
?? Nullish — falsy passes through 0 ?? "default" 0
??= Nullish assignment x ??= "init" "init"

Optional Chaining — ?.

The ?. operator safely reads a property deep inside a chain of objects. If any part of the chain is null or undefined, the entire expression short-circuits and returns undefined — instead of throwing a TypeError: Cannot read properties of null.

❌ Before ES2020 — Defensive Guard
const city = user
 && user.address
 && user.address.city;

// Verbose and hard to maintain
✅ After ES2020 — Optional Chaining
const city =
 user?.address?.city;

// Clean, readable, safe
obj?.prop
Property Access
Access a named property on a potentially nullish object without throwing.
user?.name → undefined
obj.fn?.()
Method Call
Call a method only if it exists on the object — silently skips if missing.
obj.greet?.() → undefined
arr?.[n]
Array Indexing
Access an array element safely when the array itself might be null or undefined.
items?.[0] → undefined
a?.b?.c
Deep Chaining
Chain multiple ?. operators to traverse deeply nested structures.
res?.data?.user?.id
JavaScript — Optional Chaining (?.) Examples
// ── Setup: deeply nested object ──────────────────────────────
const user = {
name: "Alice",
address: { city: "Vadodara", pincode: "390001" },
greet() { return `Hi, I'm ${this.name}`; }
};

// ── Property access ───────────────────────────────────────────
user?.address?.city; // "Vadodara"
user?.profile?.avatar; // undefined (no throw!)
user?.address?.country; // undefined (key doesn't exist)

// ── Method call ──────────────────────────────────────────────
user?.greet(); // "Hi, I'm Alice"
user?.sayBye?.(); // undefined — method doesn't exist, no error

// ── Array indexing ────────────────────────────────────────────
const items = ["a", "b", "c"];
items?.[0]; // "a"
items?.[10]; // undefined (out of bounds, no throw)

const empty = null;
empty?.[0]; // undefined — short-circuits immediately

// ── Real-world: API response traversal ───────────────────────
const res = { data: null }; // Server returned null for data
res?.data?.users?.[0]?.name; // undefined — no error thrown

// ── Short-circuit prevents side effects ──────────────────────
let count = 0;
null?.[count++]; // count stays 0 — expression never evaluated
Short-Circuit Behaviour
When ?. encounters null or undefined, the entire rest of the expression is never evaluated. This means any function calls or side effects to the right of the short-circuit point are also skipped — which is exactly what you want for performance and predictability.

Nullish Coalescing — ??

The ?? operator returns the right-hand side value when the left-hand side is null or undefined. Unlike ||, it does not treat other falsy values like 0, "", or false as triggers for the fallback — making it the precise tool for default values.

||
Triggers on ANY falsy value
null || "def" "def"
undefined || "def" "def"
0 || "def" "def" ⚠
"" || "def" "def" ⚠
false || "def" "def" ⚠
??
Only null / undefined trigger fallback
null ?? "def" "def"
undefined ?? "def" "def"
0 ?? "def" 0 ✓
"" ?? "def" "" ✓
false ?? "def" false ✓
JavaScript — Nullish Coalescing (??) Examples
// ── Basic usage ───────────────────────────────────────────────
null ?? "default"; // "default"
undefined ?? "default"; // "default"
0 ?? "default"; // 0 — 0 is NOT null/undefined!
"" ?? "default"; // "" — empty string passes through
false ?? "default"; // false — false passes through
"hello" ?? "default"; // "hello"

// ── The danger of || for numeric config values ───────────────
const config = { timeout: 0, retries: 0 };

const timeoutBad = config.timeout || 3000; // 3000 ❌ (0 is valid!)
const timeoutGood = config.timeout ?? 3000; // 0 ✅

// ── User settings example ─────────────────────────────────────
function getVolume(settings) {
return settings?.volume ?? 50; // 50 only if volume is null/undefined
}

getVolume({ volume: 0 }); // 0 ✅ (muted — intentional!)
getVolume({ volume: 80 }); // 80
getVolume({}); // 50 (no volume key → undefined → fallback)
getVolume(null); // 50 (null settings → fallback)

Logical Assignment Operators

ES2021 introduced three logical assignment operators that combine a logical operation with assignment. They're shorthand for very common conditional assignment patterns.

??=
Nullish Assignment
Assigns only if the current value is null or undefined. The most useful of the three.
x ??= "init"
||=
Logical OR Assignment
Assigns if the current value is falsy (includes 0, "", false, null, undefined).
x ||= "fallback"
&&=
Logical AND Assignment
Assigns only if the current value is truthy — updates an already-set value.
x &&= transform(x)
JavaScript — Logical Assignment (??=, ||=, &&=)
// ── ??= Nullish assignment ────────────────────────────────────
let user = { name: "Alice", score: null };

user.score ??= 0; // score is null → assigned 0
user.name ??= "Guest"; // name is "Alice" → NOT changed

console.log(user); // { name: "Alice", score: 0 }

// ── ||= Logical OR assignment ─────────────────────────────────
let count = 0;
count ||= 10; // count is 0 (falsy) → assigned 10 ⚠ may be unintended!

let label = "";
label ||= "Unnamed"; // empty string is falsy → "Unnamed" ⚠

// ── &&= Logical AND assignment ───────────────────────────────
let text = "hello";
text &&= text.toUpperCase(); // text is truthy → "HELLO"

let empty = null;
empty &&= empty.toUpperCase(); // empty is falsy → stays null (no error!)

// ── Equivalent long-form for reference ───────────────────────
x ??= y; // same as: if (x === null || x === undefined) x = y;
x ||= y; // same as: if (!x) x = y;
x &&= y; // same as: if (x) x = y;
When to Prefer ??= over ||=
Prefer ??= whenever the variable might legitimately hold a falsy value like 0, "", or false. Using ||= in those cases will overwrite perfectly valid data. Use ||= only when you explicitly want the fallback to trigger on any falsy value.

Combining ?. and ??

The real power appears when you chain both operators together. ?. handles the safe traversal while ?? provides the fallback — a pattern that eliminates most defensive null-checking boilerplate in real API data handling.

JavaScript — ?. and ?? Combined Patterns
// ── API response with uncertain shape ─────────────────────────
const apiRes = {
status: 200,
data: { user: { name: "Bob", age: 0 } }
};

const name = apiRes?.data?.user?.name ?? "Anonymous"; // "Bob"
const age = apiRes?.data?.user?.age ?? 18; // 0 ✅ (not 18 — 0 is valid!)
const city = apiRes?.data?.user?.city ?? "Unknown"; // "Unknown" (key absent)

// ── Optional method call + nullish default ─────────────────────
const label = btn?.getLabel?.() ?? "Click me";

// ── Callback pattern ──────────────────────────────────────────
function run(opts) {
const delay = opts?.delay ?? 300;
const retries = opts?.retries ?? 3;
const verbose = opts?.verbose ?? false;

opts?.onStart?.(); // call only if onStart exists
}

run(null); // safe — delay=300, retries=3, verbose=false
run({ delay: 0 }); // delay=0 ✅ (not overridden to 300!)

// ── Chaining with array methods ───────────────────────────────
const users = null;
const first = users?.find(u => u.admin)?.name ?? "No admin found";
// "No admin found" — no error despite null users
Operator Precedence Note
You cannot use ?? directly alongside || or && without parentheses — JavaScript will throw a SyntaxError to prevent ambiguity. Always use explicit parentheses when mixing: (a ?? b) || c or a ?? (b || c).

Try It — Live Editor

Experiment with Optional Chaining and Nullish Coalescing below. Try changing the values to null, 0, "", and observe how ?? and || behave differently — all without leaving this page.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These patterns appear constantly in real-world JavaScript — React components, Vue composables, API data handling, and Node.js config loading. Master these and you'll write noticeably cleaner code.

JavaScript — Real-World Recipes
// ── 1. Safe event handler ─────────────────────────────────────
document.querySelector('#btn')?.addEventListener('click', handler);
// No error if #btn doesn't exist in the DOM

// ── 2. Component prop defaults (React-style) ──────────────────
function Button({ label, size, onClick }) {
const text = label ?? "Submit";
const btnSize = size ?? "md";
const handler = onClick ?? (() => {});
}

// ── 3. Config with numeric 0 values ──────────────────────────
function createTimer(cfg) {
return {
delay: cfg?.delay ?? 1000, // 0ms delay is valid!
interval: cfg?.interval ?? 500,
repeat: cfg?.repeat ?? true,
};
}

// ── 4. Lazy initialization with ??= ───────────────────────────
const cache = {};
function get(key, compute) {
cache[key] ??= compute(); // compute only if not already cached
return cache[key];
}

// ── 5. Dynamic feature flags ──────────────────────────────────
const flags = null; // not yet loaded
const darkMode = flags?.darkMode ?? true;
const maxItems = flags?.maxItems ?? 10;

// ── 6. Safe array find ────────────────────────────────────────
const admins = getAdmins(); // might be null
const firstAdmin = admins?.find(u => u.role === 'admin')?.name ?? "None";
⚡
Free Resource
Download our JavaScript ES6+ Cheat Sheet
Optional chaining, nullish coalescing, destructuring & more — one printable page.
Get Sheet
Quick Check
What does null?.name return in JavaScript?
Quick Check
What does 0 ?? "default" evaluate to?
Quick Check
Which operator should you use to safely call a method that might not exist?
Chapter Summary
  • The Optional Chaining operator ?. safely accesses nested properties, methods, and array elements. If any part of the chain is null or undefined, the expression short-circuits and returns undefined instead of throwing a TypeError.
  • Three forms of optional chaining: obj?.prop (property), obj.fn?.() (method call), and arr?.[n] (array element). All short-circuit silently on null / undefined.
  • The Nullish Coalescing operator ?? returns the right-hand value only when the left side is null or undefined — it does not trigger on other falsy values like 0, "", or false.
  • Use ?? instead of || when providing defaults for values that could legitimately be 0, "", or false. Using || in those cases silently overwrites valid data.
  • The Nullish Assignment ??= assigns a value only if the current value is null / undefined. Prefer it over ||= for numeric or boolean defaults.
  • Combining ?. and ?? eliminates most defensive null-checking boilerplate: res?.data?.user?.name ?? "Anonymous" safely traverses any depth and provides a meaningful fallback in one readable expression.
  • You cannot mix ?? with || or && without explicit parentheses — JavaScript throws a SyntaxError to prevent precedence ambiguity.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel