Skip to content

Day 3: Optional Chaining & Nullish Coalescing

Write resilient, error-free code by safely accessing deep properties with ?. and setting fallbacks with ??.

const user = { profile: { address: null } };
// Optional Chaining (?.) prevents Cannot read properties of undefined
const street = user?.profile?.address?.street ?? 'No address provided';
// Nullish Coalescing (??) only triggers for null or undefined (unlike || which triggers for 0 and "")
const count = 0;
const displayCount = count ?? 10; // 0
const fallbackCount = count || 10; // 10 (undesired fallback for 0!)
  1. Compare || vs ?? on empty strings "" and number 0.
  2. Inspect deep APIs with missing keys using ?..