Optional chaining ?. & nullish ??
Handle missing data gracefully
Lesson 7 of 20 · 9 min · Module 2: Work with collections
Real data has holes: a user without an address, a setting nobody configured. Two operators let you read deep values safely and provide defaults without hiding real values like 0.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Read nested values safely with ?.
- Choose ?? over || for defaults
- Walk a dynamic path
The idea
a?.b returns undefined instead of throwing when a is null or undefined. x ?? fallback uses the fallback only when x is null or undefined, unlike ||, which also replaces 0, "" and false.
const user = { profile: null, volume: 0 };
console.log(user.profile?.city ?? "unknown");
console.log(user.volume || 50, user.volume ?? 50);
01?. stops early
user.profile?.city checks profile first. If it is null or undefined, the whole expression is undefined instead of a TypeError. ?.[key] does the same for dynamic keys.
02?? respects real values
A volume of 0 is a setting, not a missing value. 0 || 50 gives 50, which overrides the user; 0 ?? 50 keeps 0.
console.log(0 || 50, 0 ?? 50, "" || "x", "" ?? "x");50 0 x 03Do not overuse it
?. everywhere can hide bugs where data should always exist. Use it at boundaries, such as user input and API responses, where missing data is expected.
Your turn
getSetting(config, path, fallback), where path is a dotted string such as "audio.volume". Return the value at that path, or fallback if any step is missing, null or undefined. Values such as 0, false and "" are real values and must be returned.What the checks look for
- Reads nested values
- Uses the fallback for missing or null steps
- Keeps 0, false and empty strings
- Returns the fallback when the final value is null
Take this with you
?. for safe reading, ?? for honest defaults.
Go a little further
Write setSetting(config, path, value) that returns a new config object with the value set, creating missing levels.