Optional Chaining & Nullish Coalescing
Safely access nested properties and provide fallback values
Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.
UpgradeKnowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
Two operators that make working with values much cleaner.
Optional chaining (?.) — short-circuits if the left side is null or undefined: ``javascript const user = { profile: { address: { city: 'NY' } } }; user?.profile?.address?.city // 'NY' user?.settings?.theme // undefined (no error) user?.getName?.() // call method only if it exists user?.posts?.[0]?.title // safe array index access
Without optional chaining you'd need: ``javascript user && user.profile && user.profile.address && user.profile.address.city
Nullish coalescing (??) — returns the right side only if left is null or undefined: ``javascript null ?? 'default' // 'default' undefined ?? 'default' // 'default' 0 ?? 'default' // 0 (not null/undefined, so left side wins) '' ?? 'default' // '' (empty string is not null/undefined) false ?? 'default' // false
Compare with || (OR): || falls back on any falsy value (0, '', false), ?? only on null/undefined.
Combined:
javascript const city = user?.profile?.address?.city ?? 'Unknown city';
Examples
Safe API response access
Chain ?. to safely navigate deeply nested API responses
const response = {
data: {
user: { name: 'Alice', scores: [95, 88, 72] }
}
};
const firstName = response?.data?.user?.name ?? 'Guest';
const topScore = response?.data?.user?.scores?.[0] ?? 0;
const teamName = response?.data?.team?.name ?? 'No team';
console.log(firstName, topScore, teamName);
// Alice 95 No teamNullish vs OR fallback
Use ?? when 0 or empty string are valid values
const count = 0;
const label = '';
console.log(count || 'default'); // 'default' (0 is falsy)
console.log(count ?? 'default'); // 0 (0 is not null/undefined)
console.log(label || 'no label'); // 'no label' ('' is falsy)
console.log(label ?? 'no label'); // '' (empty string is not null/undefined)How well did you understand this?