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/undefinedOptional 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 checksPractical 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
| Operator | Returns default when | Use case |
|---|---|---|
|| | Any falsy value (0, "", false, null, undefined, NaN) | Boolean-ish defaults |
?? | Only null or undefined | Preserving valid falsy values |
?. | Accessing nested props safely | Deep 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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.