Optional Chaining & Nullish Coalescing
?. safely navigates potentially null/undefined objects, while?? provides smart fallbacks that respect valid falsy values like 0, false, and ''.
What does ?. do in JavaScript?
Optional chaining ?. stops and returns undefined if the value before it is null or undefined, instead of throwing an error. user?.address?.city safely reads deeply nested data. Pair it with the nullish coalescing operator ?? to supply a fallback: user?.name ?? "Guest".
const city = user?.address?.city; // undefined if any part is missing
const first = list?.[0]; // arrays
callback?.(); // call only if defined
const name = user?.name ?? "Guest"; // fallback for null/undefined
const count = settings.count ?? 10; // keeps 0Optional Chaining Syntax
obj?.propProperty accessobj?.method?.()Method callarr?.[index]Array/bracket accessa?.b?.c?.dDeep chaining — stops at first nullfn?.(arg)Call function only if it exists?? vs || Comparison
0 op 'default''default'0'' op 'default''default'''false op 'x''x'falsenull op 'x''x''x'undefined op 'x''x''x'NaN op 'x''x'NaNWhen to Use Each
?.Accessing properties of API responses that might be null
response?.data?.user?.name??Default values for config options that may be 0 or false
config?.timeout ?? 5000||Default values where you want ANY falsy value to trigger fallback
title || 'Untitled'??=Initialize a variable only if it's currently null/undefined
cache ??= {}; cache[key] ??= [];Common Pitfalls
Interactive Examples
Code Editor
<pre id="out"></pre>Preview
Optional chaining and nullish coalescing — step by step
Optional chaining ?. — safe property access
obj?.prop returns undefined instead of throwing a TypeError if obj is null or undefined. Works for nested access (user?.address?.city), method calls (user?.getName()), and array indexing (arr?.[0]). The entire chain short-circuits at the first null/undefined — subsequent parts are not evaluated. Eliminates defensive && chains.
🎯 Quick Check
What does 0 ?? 'default' return?
Optional Chaining and Nullish Coalescing: summary
Key points
?.only guards againstnullandundefined, not other wrong types.- Don't overuse it: if a value should always exist, a loud error helps you find the bug.
??=assigns only when the variable isnullorundefined.
Frequently asked questions
›What is the difference between ?? and ||?
|| falls back for any falsy value (0, "", false). ?? falls back only for null and undefined.