โ“ JavaScript

Optional Chaining & Nullish Coalescing โ€” Kill the undefined Errors

๐Ÿ“… Jul 4, 2026 โฑ 2 min read

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

โ† All Articles