JavaScriptFundamental (ES6), part 1
Optional chaining (?.) with methods and arrays in JavaScript
39 Optional chaining
fairRead down a path that may not exist using ?., on a property, an index and a method call. Then work out how much of the chain is skipped when a link is missing, and which values count as missing.
Stuck? Three hints, smallest first
- 1.
a?.byieldsundefinedwhenaisnullorundefined, instead of throwing. - 2. For an index or a call the dot stays:
a?.[i]anda?.(). - 3. It short-circuits the whole rest of the chain, so nothing further along is even evaluated.
const attempt = (fn) => {
try { return fn(); } catch (e) { return e.constructor.name; }
};
const parses = (src) => {
try { new Function(src); return 'parsed'; } catch (e) { return e.constructor.name; }
};
const order = {
id: 7,
buyer: { name: 'Emeka' },
lines: [{ item: 'rice' }],
count: 0,
};
const present = order.buyer?.name;
const absent = order.seller?.name;
const unguarded = attempt(() => order.seller.name);
const indexed = order.lines?.[0]?.item;
const past = order.lines?.[5]?.item;
const calledMissing = order.describe?.();
const calledUnguarded = attempt(() => order.describe());
let evaluated = 0;
const idx = () => { evaluated++; return 0; };
const shortCircuit = order.seller?.lines[idx()];
const onZero = order.count?.toFixed(1);
const notAFunction = attempt(() => order.buyer.name?.());
const asTarget = parses('const o = {}; o?.a = 1;');
console.log('present :', present, '| absent:', absent);
console.log('unguarded :', unguarded);
console.log('index :', indexed, '| past the end:', past);
console.log('call :', calledMissing, '| unguarded:', calledUnguarded);
console.log('skipped :', shortCircuit, 'and idx() ran', evaluated, 'times');
console.log('on zero :', onZero, '<- 0 is not nullish');
console.log('not a fn :', notAFunction, '| as a target:', asTarget);
Output
9 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 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a present link reads normally', present, 'Emeka');
test('a missing one yields undefined instead of throwing', absent === undefined, true);
test('the same read without the guard throws', unguarded, 'TypeError');
test('?.[] guards an index the same way', [indexed, String(past)], ['rice', 'undefined']);
test('?.() guards a method that is not there', [calledMissing === undefined, calledUnguarded], [true, 'TypeError']);
test('one nullish link skips the rest of the chain, unevaluated', [evaluated, String(shortCircuit)], [0, 'undefined']);
test('only null and undefined short-circuit, so zero carries on', onZero, '0.0');
test('it does not make a non-function callable', notAFunction, 'TypeError');
test('and an optional chain may not be assigned to', asTarget, 'SyntaxError');
The short-circuit assertion is the part that is easy to get wrong: order.seller?.lines[idx()] does not throw on lines being undefined, because once seller is nullish the entire remaining chain is abandoned and idx() is never called. So one ?. guards everything to its right, and writing a?.b?.c?.d when only a can be missing is noise.
The two limits are worth remembering. It tests for null and undefined only — 0, '' and false proceed — and ?.() means "if this is nullish, skip", not "if this is callable". A property holding a string still throws when you try to call it. Used everywhere, ?. also hides real bugs: it is a tool for genuinely optional data, not a way to silence a path that should exist.