# Optional Chaining & Nullish Coalescing

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

Subject: JavaScript | Lesson 47 of 63 | 6 min read
Interactive lesson: https://codewithanimation.in/javascript/optional-chaining-nullish
Previous: [ES Modules: import & export](https://codewithanimation.in/javascript/modules-esm.md) | Next: [Symbols & Well-Known Symbols](https://codewithanimation.in/javascript/symbols-and-well-knowns.md)

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

## Common mistake: The OR (||) Trap

Wait, why not just use the logical OR operator (`||`) for fallbacks?

The `||` operator triggers on **any falsy value**. If a user's score is exactly `0`, writing `const score = user.score || 10` will accidentally overwrite their valid `0` with `10` because `0` is falsy!

The `??` operator only triggers on `null` or `undefined`, making it perfectly safe for `0`, `""`, and `false`.

## Tip: Functions and Arrays

Optional chaining works on functions and arrays too! You can safely call an optional function with `callback?.()` or safely access an array index with `users?.[0]?.name`.

## Try it: 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 animation is on the lesson page and is not part of this text version: https://codewithanimation.in/javascript/optional-chaining-nullish

## Check yourself

### Question 1

What happens when `user.profile` is undefined and you evaluate `user?.profile?.settings`?

- A. It short-circuits at 'profile' and returns undefined without an error.
- B. It throws a TypeError.
- C. It returns null.

Correct answer: A

Optional chaining evaluates from left to right. The moment it hits `undefined`, the entire expression resolves to `undefined`.

- Why not B: Incorrect. The `?.` prevents the TypeError.
- Why not C: Incorrect. Optional chaining short-circuits to `undefined`, not `null`.

### Question 2

Why is `??` generally preferred over `||` when assigning default values to numbers or booleans?

- A. Because `??` only triggers on null/undefined, preserving valid falsy values like 0 or false.
- B. Because `??` executes faster in the browser engine.
- C. Because `||` is deprecated in modern JavaScript.

Correct answer: A

If you have a settings object `let volume = 0`, writing `volume || 100` would accidentally reset the volume to 100 because 0 is falsy. `volume ?? 100` correctly keeps it at 0.

- Why not B: Incorrect. The speed difference is negligible; it's about logic safety.
- Why not C: Incorrect. `||` is highly useful for boolean logic, just dangerous for strict fallbacks.

### Question 3

Which of the following is the correct syntax to optionally call a function named `onSuccess` that might not exist?

- A. onSuccess?.()
- B. onSuccess?()
- C. onSuccess(?. )

Correct answer: A

This is a very common pattern in React component props: `props.onClick?.()` safely executes the click handler only if the parent provided it.

- Why not B: Incorrect. You must include the dot before the parentheses.
- Why not C: Incorrect syntax.

## 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?.()`
