Skip to main content
Practice Problems

Optional chaining (?.) and nullish coalescing (??) in JavaScript

Optional Chaining (?.)

The optional chaining operator ?. allows you to safely access deeply nested properties without checking each level for null or undefined. If any part is null/undefined, the expression short-circuits and returns undefined.


Without Optional Chaining

javascript
// ❌ Verbose and error-prone const city = user && user.address && user.address.city; // ❌ Will throw if user or address is null/undefined const city = user.address.city; // TypeError!

With Optional Chaining

javascript
// βœ… Safe and clean const city = user?.address?.city; // undefined if any part is null/undefined

Optional Method Calls

javascript
const result = obj.method?.(); // Call only if method exists const item = arr?.[0]; // Access array index safely const value = map?.get?.("key"); // Chain multiple checks

Practical Examples

javascript
// API response const userName = response?.data?.user?.name ?? "Unknown"; // Event handler document.querySelector("#btn")?.addEventListener("click", handler); // Optional callback function fetchData(url, onSuccess) { fetch(url) .then(res => res.json()) .then(data => onSuccess?.(data)); }

Nullish Coalescing (??)

The ?? operator returns the right-hand operand when the left-hand operand is null or undefined β€” and only those two values.

?? vs ||

javascript
// || treats ALL falsy values as "empty" 0 || "default"; // "default" (0 is falsy!) "" || "default"; // "default" (empty string is falsy!) false || "default"; // "default" // ?? only treats null/undefined as "empty" 0 ?? "default"; // 0 βœ… "" ?? "default"; // "" βœ… false ?? "default"; // false βœ… null ?? "default"; // "default" undefined ?? "default"; // "default"

When to Use ??

javascript
// βœ… Settings where 0 or "" are valid values const port = config.port ?? 3000; const name = user.name ?? "Anonymous"; const count = response.count ?? 0; // ❌ Don't use || here β€” it would ignore valid 0 const timeout = settings.timeout || 5000; // Bug if timeout is 0! const timeout = settings.timeout ?? 5000; // Correct βœ…

Nullish Coalescing Assignment (??=)

javascript
let user = { name: "Alice" }; user.name ??= "Default"; // "Alice" (not null, so unchanged) user.age ??= 25; // 25 (undefined, so assigned) user.score ??= 0; // 0 (undefined, so assigned)

Combining ?. and ??

javascript
const displayName = user?.profile?.displayName ?? "Guest"; const theme = settings?.appearance?.theme ?? "light"; const items = response?.data?.items ?? [];

Comparison Table

OperatorReturns default whenUse case
||Any falsy value (0, "", false, null, undefined, NaN)Boolean-ish defaults
??Only null or undefinedPreserving valid falsy values
?.Accessing nested props safelyDeep property access

Important:

Use ?? instead of || when 0, "", or false are valid values. Combine ?. with ?? for safe property access with defaults: user?.name ?? "Guest".

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems