JavaScript · Level 2 Objects

Optional Chaining

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 ||

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

Write cityOf(user) that returns the user's address.city, or "Unknown" if any part is missing, for example cityOf({ name: "Bob" }) returns Unknown.

solution.js
Test Suites Pending
Output