Overview
Read deeply nested API data without crashing on a missing field, and supply a fallback when the value isn't there.
- ?. stops at null or undefined
- ?? gives a fallback for null or undefined
- ?? versus ||
Short Course
a?.b gives undefined instead of throwing when a is null or
undefined. ?? swaps in a fallback only for null or undefined. Trap:
|| also replaces 0 and "".
const order = { customer: null, items: 0 };
order.customer.name; // TypeError!
order.customer?.name; // undefined
order.customer?.name ?? "Guest"; // "Guest"
order.items ?? 5; // 0
order.items || 5; // 5 — the 0 was lost
Task
Write cityOf(user) that returns the user's address.city, or "Unknown" if
any part is missing, for example cityOf({ name: "Bob" }) returns Unknown.
Test Suites
Pending
Next
Output