Optional chaining (?.) stops reading a property when the value is null or undefined, and nullish coalescing (??) gives a fallback only for null or undefined, unlike ||.
The short answer
#?. is optional chaining: it reads a property, index or method only if the value before it is not null or undefined, and otherwise returns undefined instead of throwing. ?? is nullish coalescing: it returns the right-hand value only when the left-hand value is null or undefined. Together they replace long chains of checks.
_10const city = user?.address?.city ?? 'Unknown';
Why it happens
#Reading a property of null or undefined throws a TypeError, so code that handles API data used to be full of guards like user && user.address && user.address.city. Optional chaining does that check for you at each ?..
For defaults, developers traditionally used ||. The problem is that || falls back for every falsy value, including 0, an empty string '', false and NaN. Those are often perfectly valid values. ?? only treats null and undefined as missing.
_10const settings = { volume: 0, name: '' };_10_10settings.volume || 50; // 50, which is wrong: 0 was a real setting_10settings.volume ?? 50; // 0_10_10settings.name || 'Guest'; // 'Guest'_10settings.name ?? 'Guest'; // ''
How to fix it
#Use ?. for properties, indexes and calls
Optional chaining has three forms.
_10user?.profile; // property_10user?.['first-name']; // computed key or index_10items?.[0]; // array index_10user.getName?.(); // call only if the method exists_10onChange?.(value); // call an optional callback
It short-circuits. As soon as a ?. finds null or undefined, the rest of the expression is skipped, so a?.b.c.d does not throw if a is missing. It does still throw if a exists but a.b is undefined, because there is no ?. after b.
Use ?? for defaults
Pick ?? when 0, '' or false are valid values that should be kept.
_10function createServer(options) {_10 const port = options.port ?? 3000;_10 const retries = options.retries ?? 3;_10 const verbose = options.verbose ?? false;_10 return { port, retries, verbose };_10}_10_10createServer({ retries: 0 }); // retries stays 0
Still use || when you really do want to replace any falsy value, for example turning an empty input into a placeholder.
Use ??= to fill in a missing value
The logical nullish assignment operator assigns only when the current value is null or undefined.
_10const cache = {};_10cache.users ??= [];_10cache.users.push('ada');
Combine them
?. returns undefined when something is missing, which is exactly what ?? looks for, so they work well together.
_10const firstTag = post?.tags?.[0] ?? 'untagged';_10const count = response?.data?.items?.length ?? 0;
Common pitfalls
#- Mixing ?? with || or && without brackets.
a || b ?? cis aSyntaxError. Add parentheses to say which you mean:(a || b) ?? c. - Assigning through optional chaining.
user?.name = 'Ada'is aSyntaxError. Optional chaining is only for reading and calling. - Hiding real bugs. If a value should always exist, a
?.turns a loud error into a quietundefinedthat surfaces somewhere else. Use it for data that is genuinely optional. - Undeclared variables.
missingVar?.foostill throws aReferenceErrorifmissingVarwas never declared. Optional chaining guards againstnullandundefinedvalues, not missing variables. - ?. does not check the type.
count?.toFixed()still throws ifcountis a string, because strings have notoFixedmethod. Onlynullandundefinedare skipped. - Default parameters are similar but not the same. A default parameter like
function f(x = 1)only applies forundefined, while??also coversnull.
Related reading
#Was this resource helpful?