Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Optional chaining with ?? fallbacks in JavaScript

70 Optional chaining, and the place ?? beats ||

fair

Read values out of a half-filled settings object without a single && guard: ?. for a property, ?.[] for a computed key, ?.() for a method that may not exist. Then supply fallbacks with ?? and show the two cases where || gives the wrong answer.

Stuck? Three hints, smallest first
  1. 1. ?. stops for null and undefined only, and when it stops the whole rest of the chain is skipped, not just the next step.
  2. 2. || replaces anything falsy, which includes 0, '', NaN and false. ?? replaces only null and undefined.
  3. 3. A short-circuited ?.() never evaluates its arguments, so nothing inside the parentheses runs.

The answer

const stall = {
  owner: { name: 'Adaeze', phone: null },
  display: { pageSize: 0, label: '', printable: false },
  tools: { print: (what) => `printing ${what}` },
  address: null,
};

const city = stall.address?.city;
const deeper = stall.address?.city.lga.zone;   // the WHOLE chain is skipped
const dynamic = stall.display?.['pageSize'];
const printed = stall.tools.print?.('receipt');
const emailed = stall.tools.email?.('receipt');

let sideEffects = 0;
const argument = () => {
  sideEffects++;
  return 'x';
};
const skipped = stall.tools.email?.(argument());
const ran = stall.tools.print?.(argument());

const pageSize = stall.display.pageSize ?? 20;
const pageSizeWrong = stall.display.pageSize || 20;
const label = stall.display.label ?? 'Ikeja stall';
const labelWrong = stall.display.label || 'Ikeja stall';
const phone = stall.owner.phone ?? 'none';
const printable = stall.display.printable ?? true;

let mixed;
try {
  mixed = new Function('return null ?? 1 || 2;')();
} catch (error) {
  mixed = error.constructor.name;
}

let unguarded;
try {
  unguarded = stall.address.city?.name;   // ?. after the null, not before it
} catch (error) {
  unguarded = error.constructor.name;
}

console.log('chain  :', city, deeper, dynamic);
console.log('calls  :', printed, emailed, '| side effects:', sideEffects);
console.log('?? vs ||:', [pageSize, pageSizeWrong], [label, labelWrong]);
console.log('mixed  :', mixed, '| unguarded:', unguarded);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('a missing branch reads as undefined instead of throwing', [city, dynamic], [undefined, 0]);
test('and when ?. short-circuits it abandons every step after it', deeper, undefined);
test('?.() calls a method only if it is there', [printed, emailed], ['printing receipt', undefined]);
test('a short-circuited call never even evaluates its arguments', [skipped, ran, sideEffects], [undefined, 'printing x', 1]);
test('?? keeps a real 0 and a real empty string; || throws both away', [pageSize, pageSizeWrong, label, labelWrong], [0, 20, '', 'Ikeja stall']);
test('?? does replace null, and leaves false alone', [phone, printable], ['none', false]);
test('mixing ?? and || without parentheses is a syntax error, on purpose', mixed, 'SyntaxError');
test('?. guards the step it is written on, not the one before it', unguarded, 'TypeError');

?. replaces the a && a.b && a.b.c ladder, and it short-circuits the entire chain rather than one link: once stall.address?. sees null, the .city.lga.zone that follows is never evaluated at all. That is why the long chain above is safe with only one question mark in it.

It guards the step it sits on. stall.address.city?.name still throws, because the crash happens at .city on a null, before the ?. is reached. Put the mark where the value might be missing, and only there — a chain peppered with ?. at every step hides real bugs behind quiet undefineds.

?? exists because || answers the wrong question. A page size of 0, an empty label, a temperature of 0 and a false flag are all legitimate values that || silently overwrites with your default. ?? asks only "was this absent". The language refuses to let you mix ?? with && or || unparenthesised, precisely because the precedence would be a coin toss for the reader.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.