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.
?. for safe property
access?? — fallback for
null/undefined only?? vs || — the critical
difference??=,
||=, &&=
?. and ?? for
real-world API dataOverview — 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.
?.
undefined instead of throwing a
TypeError when a property doesn't exist.
??null or undefined — ignores 0, "",
false.
??=null or undefined. Also: ||= and
&&=.
?. 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.
const city = user
&& user.address
&& user.address.city;
// Verbose and hard to maintain
const city =
user?.address?.city;
// Clean, readable, safe
?. operators to traverse deeply nested
structures.// ── 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?. 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.
// ── 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.
null or
undefined. The most useful of the three.
// ── ??= 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;??= over ||=
??= 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.
// ── 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?? 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.
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.
// ── 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";
null?.name return in JavaScript?0 ?? "default" evaluate to?- The Optional Chaining operator
?.safely accesses nested properties, methods, and array elements. If any part of the chain isnullorundefined, the expression short-circuits and returnsundefinedinstead of throwing aTypeError. - Three forms of optional chaining:
obj?.prop(property),obj.fn?.()(method call), andarr?.[n](array element). All short-circuit silently onnull/undefined. - The Nullish Coalescing operator
??returns the right-hand value only when the left side isnullorundefined— it does not trigger on other falsy values like0,"", orfalse. - Use
??instead of||when providing defaults for values that could legitimately be0,"", orfalse. Using||in those cases silently overwrites valid data. - The Nullish Assignment
??=assigns a value only if the current value isnull/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 aSyntaxErrorto prevent precedence ambiguity.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.