Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Nullish coalescing with a value of 0 in JavaScript

40 Nullish coalescing and the logical assignments

fair

Supply a fallback with ?? and with || for a setting whose value is 0, and explain the difference. Then use ??=, ||= and &&=, and prove that when they do not assign, they do not write at all.

Stuck? Three hints, smallest first
  1. 1. ?? falls back on null and undefined only. || falls back on every falsy value.
  2. 2. x ??= v is x ?? (x = v): if the test fails, the assignment never happens.
  3. 3. Mixing ?? with || or && in one expression is a syntax error without parentheses.

The answer

const parses = (src) => {
  try { new Function(src); return 'parsed'; } catch (e) { return e.constructor.name; }
};

const given = { discount: 0, note: '', branch: null };

const withNullish = given.discount ?? 10;
const withOr = given.discount || 10;
const nullBranch = given.branch ?? 'Ikeja';
const blankNote = given.note ?? 'none';

const cfg = { retries: 0, label: null };
cfg.retries ??= 3;                                // 0 is not nullish: left alone
cfg.label ??= 'unnamed';

const loose = { retries: 0 };
loose.retries ||= 3;                              // 0 is falsy: overwritten

const stall = { owner: 'ngozi', area: undefined };
stall.owner &&= stall.owner.toUpperCase();
stall.area &&= 'never assigned';

let writes = 0;
const box = {
  _v: 'set',
  get v() { return this._v; },
  set v(value) { writes++; this._v = value; },
};
box.v ??= 'other';                                // getter is not nullish, so no write

const mixedUp = parses('const a = 1, b = 2, c = 3; return a ?? b || c;');
const parenthesised = parses('const a = 1, b = 2, c = 3; return (a ?? b) || c;');

console.log('?? on 0   :', withNullish, '| || on 0:', withOr);
console.log('?? on null:', nullBranch, '| on an empty string:', JSON.stringify(blankNote));
console.log('??=       :', cfg, '| ||=:', loose);
console.log('&&=       :', stall.owner, stall.area, 'key still there:', 'area' in stall);
console.log('setter    :', writes, 'writes, value still', box.v);
console.log('mixing    :', mixedUp, '| parenthesised:', parenthesised);

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.

9 checks

test('?? falls back only on null or undefined, so a zero setting survives', withNullish, 0);
test('while || throws away every falsy value', withOr, 10);
test('null does trigger the fallback', nullBranch, 'Ikeja');
test('and an empty string survives ?? as well', blankNote, '');
test('??= leaves a zero alone and fills a null', [cfg.retries, cfg.label], [0, 'unnamed']);
test('||= overwrites the zero', loose.retries, 3);
test('&&= assigns only where the value was already truthy', [stall.owner, stall.area === undefined], ['NGOZI', true]);
test('when the test fails there is no assignment, so a setter never runs', [writes, box.v], [0, 'set']);
test('?? may not be mixed with || without parentheses', [mixedUp, parenthesised], ['SyntaxError', 'parsed']);

value || fallback was the standard idiom for twenty years and it is wrong for any setting where 0, '' or false is a real value: a discount of zero, an empty search box, a disabled flag. ?? asks the question people actually mean — "was anything supplied?" — and leaves every other value alone.

The setter assertion shows why x ??= v is not sugar for x = x ?? v. The short-circuiting form performs no write when the test fails, so no setter fires, no proxy trap runs, and no framework re-render is triggered. The mandatory parentheses when mixing with || are deliberate: the precedence would be a coin flip for most readers, so the language makes you say which you meant.

Newsletter

New writing, when it lands.

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