AI Hints
Home›JavaScript Tutorial›JSON and Copying
JavaScript · Lesson 66 of 138

Optional Chaining

?. and ??.

⏱ 2 min read▶ Video at 1:20:29🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Data from the real world is often incomplete. A user might not have an address, or an address might not have a postcode. Reading a property of something undefined crashes your program. Two modern operators make this safe.

Optional Chaining
From the video: Optional Chaining
  • Real data has gaps
  • Reading from undefined crashes
  • Two operators fix it

Safe reading with fallbacks

Question mark dot stops and gives undefined, instead of crashing, if the thing on its left is missing. Two question marks give a fallback, but only when the left side is null or undefined. Unlike two bars, they keep real values like zero. Run it.

app.jsjavascript
const users = [
  { name: "Ana", address: { city: "Lisbon" }, score: 0 },
  { name: "Ben" },
];

for (const u of users) {
  const city = u.address?.city ?? "unknown";
  console.log(`${u.name}: ${city}`);
}

console.log(users[0].score || 10, users[0].score ?? 10);
Output
Ana: Lisbon
Ben: unknown
10 0

Use them together

Optional chaining and the nullish operator are a perfect pair. Read deeply with question mark dot, and supply a default with two question marks. Use two question marks instead of two bars whenever zero, false, or an empty string are valid values.

keyvalue
a?.bundefined if a is missing
a?.b?.csafe all the way
x ?? yy only if x is null/undefined
x || yy if x is falsy

Summary

Optional chaining reads missing properties safely, and two question marks give a fallback for null or undefined. Next, practice with a contact book.

Key takeaways
  • ?. for safe reads
  • ?? for defaults
  • ?? keeps 0 and ''
Next up: Practice: A Contact Book — objects in action