Optional Chaining and Nullish Coalescing

Difficulty: Beginner

Question

Explain the optional chaining (?.) and nullish coalescing (??) operators. How do they differ from && and ||, and when should you use each?

Answer

Optional chaining (?.) safely accesses a property, calls a method or indexes into a value that might be null or undefined: if the left side is nullish, the whole expression short-circuits to undefined instead of throwing a TypeError. Nullish coalescing (??) returns the right-hand operand only when the left is null or undefined, unlike ||, which falls back on any falsy value such as 0, '' or false. Both arrived in ES2020 and are supported in every modern browser and Node.js 14+.

The three forms of optional chaining

Short-circuiting covers the rest of the chain. In user?.address.city, if user is nullish the result is undefined and .city is never evaluated. But if user exists and address is undefined, .city still throws, so you need user?.address?.city when each level may be missing.

Why ?? is different from ||

|| treats every falsy value as missing: false, 0, -0, 0n, '', NaN, null, undefined. That causes real bugs:

Value of a`a \\'default'`a ?? 'default'
0'default'0
'''default'''
false'default'false
NaN'default'NaN
null or undefined'default''default'

If a cart's discount is legitimately 0 rupees, discount || 50 silently applies a fifty rupee default. discount ?? 50 keeps the 0. Use ?? for defaults whenever 0, '' or false are valid values; use || only when any falsy value really should be replaced.

Comparison with && chains

Before ES2020 people wrote user && user.address && user.address.city. That works but returns the first falsy value it meets: if user.address is '', the result is '', not undefined. Optional chaining only checks for null and undefined, so ?. is both shorter and more precise.

Rules and gotchas

?? vs ||: keeping valid falsy values. Switch the operator between ?? and || under Tweak and watch 0 survive or get replaced.
  1. ?? checks for null/undefined only: 0 ?? "hi" returns 0.
  2. || checks truthiness: 0 || "hi" returns "hi", which loses a valid zero.
  3. Use ?? for defaults: settings.volume ?? 50 keeps a user's 0.

Code examples

Optional chaining patterns on an API response

const response = {
  data: {
    restaurant: { name: 'Meghana Foods', ratings: [4.5, 4.2] },
  },
};

console.log(response.data?.restaurant?.name);
console.log(response.data?.offers?.[0]?.code);   // offers missing
console.log(response.data?.restaurant?.ratings?.[1]);

const callbacks = { onSuccess: msg => `ok: ${msg}` };
console.log(callbacks.onSuccess?.('paid'));
console.log(callbacks.onError?.('failed'));      // no onError, no crash

// Short-circuit: the function is never called when user is null
const user = null;
let calls = 0;
user?.profile[(calls++, 'name')];
console.log('calls:', calls);

Each ?. stops evaluation when the value to its left is nullish, including any expressions later in the chain. Optional calls are handy for callbacks that may not be provided.

?? vs || and logical assignment

function buildConfig(options) {
  return {
    retries: options.retries ?? 3,
    retriesWrong: options.retries || 3,
    label: options.label ?? 'Untitled',
    verbose: options.verbose ?? true,
  };
}

console.log(buildConfig({ retries: 0, label: '', verbose: false }));

const settings = { timeout: null, theme: 'dark' };
settings.timeout ??= 5000; // assigned: was null
settings.theme ??= 'light'; // skipped: already set
console.log(settings);

?? respects intentional zero, empty string and false values, while || overwrites them. The ??= operator assigns only when the current value is null or undefined.

Key points

Common follow-up questions

Interview tips

Concepts covered

Optional Chaining, Nullish Coalescing, Short-circuit Evaluation, Falsy Values, Logical Assignment

More JavaScript Interview questions