Optional Chaining and Nullish Coalescing in JavaScript
?. and ?? make null-safe access readable. Learn the syntax, the difference from ||, and the cases where they hide bugs.
By Velloreth
Optional chaining
Accesses a property only if the value is not null or undefined.
const user = { name: 'Ada', address: { city: 'London' } };
user.address?.city; // 'London'
user.contact?.email; // undefined, no error
user.contact.email; // TypeError: Cannot read properties of undefined
Without optional chaining, the third line throws. With it, the second line returns undefined.
Deep access
const city = response?.data?.user?.address?.city;
Each ?. short-circuits the rest of the chain. If response is undefined, the whole expression is undefined and nothing after it is evaluated.
Method calls
obj.method?.();
This calls method only if it exists. The distinction matters:
obj.method?.(); // checks whether method exists
obj?.method(); // checks whether obj exists, then calls method
If obj exists but method does not, the first is safe and the second throws.
Bracket notation
obj?.[key];
arr?.[0];
Useful for dynamic keys and for array access when the array might be missing.
With delete
delete obj?.prop;
Does nothing if obj is null or undefined.
Nullish coalescing
Provides a fallback only when the left side is null or undefined.
const port = config.port ?? 3000;
The difference from ||
This is the most important distinction.
const count = 0;
count || 10; // 10 — 0 is falsy
count ?? 10; // 0 — 0 is not nullish
const name = '';
name || 'Anonymous'; // 'Anonymous' — '' is falsy
name ?? 'Anonymous'; // '' — '' is not nullish
The rule:
| Value | || falls back? | ?? falls back? |
|---|---|---|
null | Yes | Yes |
undefined | Yes | Yes |
0 | Yes | No |
'' | Yes | No |
false | Yes | No |
NaN | Yes | No |
Use ?? when 0, '', or false are valid values. Use || when you genuinely want any falsy value to trigger the fallback.
// Bug: a quantity of 0 becomes 1
const quantity = input.quantity || 1;
// Fixed
const quantity = input.quantity ?? 1;
Combining with optional chaining
const city = user?.address?.city ?? 'Unknown';
This is the standard pattern for reading a possibly-missing value with a default.
Assignment operators
config.port ??= 3000; // assign only if null or undefined
config.retries ||= 3; // assign only if falsy
config.name &&= 'set'; // assign only if truthy
??= is the nullish version and is usually what you want for defaults.
Short-circuiting
Both operators short-circuit, so the right side is not evaluated when the left decides the result.
const result = cache.get(key) ?? expensiveCompute();
If the cache has a value, expensiveCompute is not called. This makes ?? useful for lazy defaults.
const value = obj?.deeply?.nested?.property;
If any link is missing, the rest is not evaluated, so there is no error.
When they hide bugs
Optional chaining is a tool for genuinely optional data. Used carelessly, it hides missing data.
// Suspicious: why would user be missing here?
const name = user?.name ?? 'Unknown';
If user should always exist at this point, the ?. is masking a bug. The code silently produces 'Unknown' instead of failing where the problem is.
The judgement: use ?. when the value is genuinely optional by design — an optional config field, a nullable API response, a feature that may not be present. Do not use it to avoid thinking about whether a value can be missing.
A useful test: if the fallback value would be a bug in production, the ?. is hiding something.
Common patterns
API responses
const items = response?.data?.items ?? [];
The ?? [] ensures the result is always an array, so downstream code can call .map without a guard.
Optional callbacks
onSuccess?.(result);
Calls the callback only if it was provided.
Feature detection
if (window?.IntersectionObserver) {
// use it
}
Config with defaults
const config = {
host: env.HOST ?? 'localhost',
port: env.PORT ?? 3000,
debug: env.DEBUG ?? false,
};
Array access
const first = items?.[0]?.name;
Gotchas
Cannot assign through optional chaining.
obj?.prop = 1; // SyntaxError
Cannot use it on the left of a destructuring assignment.
const { a } = obj?.nested; // works — the right side is fine
const { a } = obj?.nested ?? {}; // safer
Mixing ?? with || or && needs parentheses.
a ?? b || c; // SyntaxError
(a ?? b) || c; // valid
a ?? (b || c); // valid
The restriction exists because the precedence would be ambiguous.
Optional chaining does not protect against other errors.
obj?.method(); // if method exists but throws, the error propagates
It only guards against null and undefined.
It does not make a value defined.
const name = user?.name; // still undefined if user is undefined
name.toUpperCase(); // still throws
The chain must continue, or a fallback must be provided.
Refactoring with optional chaining
Optional chaining often replaces a chain of guards, which makes the intent clearer.
// Before
let city;
if (user && user.address && user.address.city) {
city = user.address.city;
}
// After
const city = user?.address?.city;
The second version is shorter and states the same thing: read the city if the path exists.
The same applies to function calls and array access.
// Before
if (callbacks && callbacks.onSuccess) {
callbacks.onSuccess(result);
}
// After
callbacks?.onSuccess?.(result);
When a guard is better
Optional chaining is not always the right replacement for a guard.
When you need to distinguish missing from falsy. Optional chaining returns undefined for a missing path, which is the same as a present-but-undefined value. If the distinction matters, check explicitly.
if (Object.hasOwn(user, 'address')) {
// the property exists, even if its value is undefined
}
When the missing case needs different handling. A guard can branch; optional chaining can only produce a value.
if (!user) {
redirectToLogin();
return;
}
const name = user.name; // safe, and the missing case is handled
When the value should always exist. If user is guaranteed at that point, user?.name hides a bug. Let it throw, and fix the real problem.
The judgement: use ?. when the value is genuinely optional, and a guard when the missing case needs its own handling.
Optional chaining in TypeScript
TypeScript understands optional chaining and narrows types accordingly.
interface User {
name: string;
address?: { city: string };
}
const city = user.address?.city; // string | undefined
The result type includes undefined, which forces the caller to handle the missing case. This is the main benefit: the type system tracks the possibility of absence.
Combining with ?? removes the undefined from the type.
const city = user.address?.city ?? 'Unknown'; // string
A common mistake is using ?. where the type says the value is always present. TypeScript will not complain, but the check is dead code, and it hides the fact that the value is guaranteed. If the type says string, use user.name directly.
Practical guidance
- Use
?.for genuinely optional data, not to mask bugs. - Use
??for defaults when0,'', orfalseare valid. - Use
||for truthiness fallbacks when any falsy value should trigger. - Combine them for reading possibly-missing values with defaults.
- Use
??=for nullish default assignment. - Add parentheses when mixing
??with||or&&. - Remember
?.only guards null and undefined. - Ask whether the fallback would be a bug — if so, the
?.is hiding something.
For the related guides, see null-vs-undefined-vs-nil and javascript-destructuring-guide. For the broader context, error-handling-patterns and javascript-object-methods-guide.
Quotable summary
Optional chaining (?.) short-circuits to undefined when the value before it is null or undefined, instead of throwing a TypeError, and it works for property access, method calls, and bracket notation. Nullish coalescing (??) falls back only when the left side is null or undefined, unlike || which also falls back on 0, empty string, false, and NaN, so use ?? when those are valid values. Both operators short-circuit, so the right side is not evaluated when the left decides the result, which makes ?? useful for lazy defaults. Optional chaining can hide missing data, so use it for genuinely optional values rather than to paper over bugs — a useful test is whether the fallback value would itself be a bug in production.