More JavaScript answers

by Danny
Published 2 min read

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.


_10
const 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.


_10
const settings = { volume: 0, name: '' };
_10
_10
settings.volume || 50; // 50, which is wrong: 0 was a real setting
_10
settings.volume ?? 50; // 0
_10
_10
settings.name || 'Guest'; // 'Guest'
_10
settings.name ?? 'Guest'; // ''

How to fix it

#

Use ?. for properties, indexes and calls

Optional chaining has three forms.


_10
user?.profile; // property
_10
user?.['first-name']; // computed key or index
_10
items?.[0]; // array index
_10
user.getName?.(); // call only if the method exists
_10
onChange?.(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.


_10
function 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
_10
createServer({ 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.


_10
const cache = {};
_10
cache.users ??= [];
_10
cache.users.push('ada');

Combine them

?. returns undefined when something is missing, which is exactly what ?? looks for, so they work well together.


_10
const firstTag = post?.tags?.[0] ?? 'untagged';
_10
const count = response?.data?.items?.length ?? 0;

Common pitfalls

#
  • Mixing ?? with || or && without brackets. a || b ?? c is a SyntaxError. Add parentheses to say which you mean: (a || b) ?? c.
  • Assigning through optional chaining. user?.name = 'Ada' is a SyntaxError. Optional chaining is only for reading and calling.
  • Hiding real bugs. If a value should always exist, a ?. turns a loud error into a quiet undefined that surfaces somewhere else. Use it for data that is genuinely optional.
  • Undeclared variables. missingVar?.foo still throws a ReferenceError if missingVar was never declared. Optional chaining guards against null and undefined values, not missing variables.
  • ?. does not check the type. count?.toFixed() still throws if count is a string, because strings have no toFixed method. Only null and undefined are skipped.
  • Default parameters are similar but not the same. A default parameter like function f(x = 1) only applies for undefined, while ?? also covers null.
#

Was this resource helpful?