"Cannot read properties of undefined" โ JavaScript's most common crash. Two operators ended the era of nested if-guards.
Optional chaining ?.
// before const city = user && user.address && user.address.city; // after const city = user?.address?.city; // undefined instead of crash user?.getProfile?.(); // safe METHOD call (exists? then call) items?.[0]; // safe array/dynamic access data?.students?.[0]?.marks?.cn; // chains fully
Short-circuits at the first null/undefined โ the rest isn't evaluated.
Nullish coalescing ??
const perPage = settings.perPage ?? 20; // default ONLY for null/undefined
The || trap (interview favourite)
const count = data.count || 10; // โ 0 is falsy โ 0 becomes 10! const count = data.count ?? 10; // โ 0 stays 0 const name = input || "Anon"; // โ "" becomes "Anon" โ maybe wanted? const name = input ?? "Anon"; // โ "" stays ""
Rule: ?? for defaults, || only when you truly want to replace all falsy values.
Don't overdo it
Ten ?. in a row hides bugs โ if user should ALWAYS exist, let it crash loudly in development. Use ?. at genuine uncertainty boundaries: API responses, optional config, DOM queries.