Optional Chaining & Nullish Coalescing

Navigate deeply nested data safely. Learn how to prevent crash-inducing TypeErrors using the ?. and ?? operators.

JavaScript6 min readConcept 47 of 62

The Danger of Deep Objects

In modern JavaScript, you frequently work with deeply nested data (like API responses).

If you try to read user.profile.address.city, but the user hasn't set up a profile yet, JavaScript will throw a fatal TypeError: Cannot read properties of undefined (reading 'address'). This instantly crashes your app.

Optional Chaining (?.)

Historically, developers had to write terrible code to prevent this: if (user && user.profile && user.profile.address) { ... }.

**Optional Chaining (?.)** solves this elegantly. If you write user?.profile?.address?.city, JavaScript will check each level. The exact millisecond it encounters a null or undefined, it instantly "short-circuits" (stops checking) and safely returns undefined instead of throwing an error.

Nullish Coalescing (??)

Often, if a value is undefined, you want to provide a fallback default.

**Nullish Coalescing (??)** is a strict fallback operator. const city = user?.profile?.city ?? 'Unknown'; means: "Give me the city, but if it is strictly null or undefined, give me 'Unknown' instead."

The Safe Navigator

Use the control panel to randomly delete parts of the User object. Watch how the old syntax instantly throws a fatal crash, while Optional Chaining safely navigates the broken data.

The Safe Navigator

// Legacy Approach (DANGEROUS)const c1 = user.profile.address.city;
← Works safely
// Modern Approach (SAFE)const c2 = user?.profile?.address?.city ?? 'Unknown';
← Works safely
const user = {
profile: {
address: {
city: 'Tokyo'
}
}
}
Result (Legacy)
"Tokyo"
Result (Modern)
"Tokyo"
iClick Delete Profile. Notice how the legacy code violently crashes the entire app because it tries to read .address on undefined. The modern code safely short-circuits and defaults!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What happens when `user.profile` is undefined and you evaluate `user?.profile?.settings`?
  2. 2Why is `??` generally preferred over `||` when assigning default values to numbers or booleans?
  3. 3Which of the following is the correct syntax to optionally call a function named `onSuccess` that might not exist?

Remember this

  • Deeply nested property access can cause fatal TypeError crashes if a parent object is missing.
  • Optional Chaining (?.) short-circuits and safely returns undefined instead of throwing an error.
  • Nullish Coalescing (??) provides a fallback value only if the left side is null or undefined.
  • Avoid using || for fallbacks if 0, "", or false are valid data values.
  • Optional chaining also works for safely invoking functions: callback?.()

Done with this concept?

Mark it complete to track your progress. No login needed.