Optional Chaining (?.) and Nullish (??)

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — Reading What Might Not Be There

Imagine a brand-new trainer who hasn't chosen a starter Codémon yet: `trainer.starter` is `undefined`. If you try to read `trainer.starter.name`, JavaScript crashes with an error because you cannot read `.name` on `undefined`!

Instead of writing long `if` checks everywhere, use optional chaining (`?.`). If the value before `?.` is `undefined` or `null`, JavaScript stops right there and safely returns `undefined` instead of crashing:

const trainer = { name: "Sam" }; console.log(trainer.starter?.name);

Here `trainer.starter` is `undefined`, so `trainer.starter?.name` calmly evaluates to `undefined` with zero errors.

Exercise 2 — Where to Put the Question Mark

Place `?.` right after the part that might be missing. In `trainer.starter?.name`, we know `trainer` exists, so `?.` only checks whether `starter` exists before reading `.name`:

trainer.starter?.name // ok if starter is missing // still crashes if trainer itself is missing

Optional chaining also works when reading an array index (`?.[0]`) or calling a method that might not exist (`?.()`):

const trainer = { name: "Sam" }; console.log(trainer.team?.[0]); console.log(trainer.getBadges?.());

Exercise 3 — Quiz: Safe or Crash?

What does this code print?

const zap = { name: "Zap" }; console.log(zap.stats?.hp);
Options
• undefined
• 0
• An error
• null

Hint : The question mark stops the chain instead of letting it crash.

Exercise 4 — Protect the Chain

Read the starter's name without crashing when there is no starter.

Hint : One symbol both follows the link and gives up quietly when there's nothing to follow.

Exercise 5 — A Fallback Value

`undefined` is safe, but it's rarely what you want to show. The nullish operator, written `??`, supplies a fallback: it returns the left side, unless that side is `null` or `undefined`.

const trainer = { name: "Sam" }; const starterName = trainer.starter?.name ?? "none"; console.log("Starter: " + starterName);

The two work as a pair: `?.` gets you there safely, `??` decides what to show when the answer is nothing.

Exercise 6 — ?? Is Not ||

`||` also picks a fallback, but it triggers on every falsy value, including `0`, `""` and `false`. `??` triggers only on `null` and `undefined`:

const zap = { hp: 0 }; console.log(zap.hp ?? 100); console.log(zap.hp || 100);

A fainted Codémon has 0 HP, and that's a real value. `??` keeps it, `||` wrongly replaces it with 100. For numbers that can legitimately be zero, `??` is the safe choice.

Exercise 7 — Quiz: Zero Survives?

What does this code print?

const cdm = { level: 0 }; console.log(cdm.level ?? 1);
Options
• 0
• 1
• undefined
• An error

Hint : Only two values in the whole language trigger this operator.

Exercise 8 — Quiz: The Pair at Work

What does this code print?

const trainer = { name: "Sam" }; console.log(trainer.team?.length ?? 0);
Options
• 0
• undefined
• An error
• null

Hint : The first operator avoids the crash, the second replaces the empty answer.

Exercise 9 — Safe With a Fallback

Print the number of team members, or 0 when there is no team.

Hint : One symbol survives a missing link, the other replaces an empty answer.

Exercise 10 — Safe Access Cheat Sheet

`const o = { a: 0 };`. Match each expression with its value.

Items to match
• o.b?.c
• o.b?.c ?? "none"
• o.a ?? 9
• o.a || 9
Definitions
• undefined
• "none"
• 0
• 9

Exercise 11 — Robust Profile

Three save files arrive from different versions of the game, and none of them has the same fields. Print a profile for each one without a single crash.

Step 1: `profile(save)` prints `"Name: X"`, using `"unknown"` when the name is missing. Step 2: it prints `"Team: N"` with the number of team members, using 0 when there is no team. Step 3: it prints `"Starter: X"` with the starter's name, using `"none"` when there is no starter. Step 4: it prints `"Badges: N"` with the badge count, using 0 when missing. Call it on the three saves, printing a blank-free profile for each.

Expected output:

Name: Sam Team: 2 Starter: Aquachu Badges: 3 Name: Lea Team: 0 Starter: none Badges: 0 Name: unknown Team: 1 Starter: none Badges: 0
Starter code
const saves = [ { name: "Sam", team: ["Aquachu", "Zap"], starter: { name: "Aquachu" }, badges: ["Rock", "Water", "Fire"] }, { name: "Lea" }, { team: ["Metachu"] } ]; // Write your function here // Use it here
Back to the course