Optional Chaining
?. and ??.
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.

- 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.
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);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.
| key | value |
|---|---|
| a?.b | undefined if a is missing |
| a?.b?.c | safe all the way |
| x ?? y | y only if x is null/undefined |
| x || y | y 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 ''