JavaScriptFundamental (ES6), part 1
Logical assignment operators (??=, ||=, &&=) in JavaScript
71 The logical assignments, and the write that never happens
fairApply defaults to a settings object with ??=, ||= and &&=, and show how differently the three treat a 0 and an empty string. Then put a counting setter behind a property and prove that a short-circuited logical assignment does not write at all — which x = x || y always does.
Stuck? Three hints, smallest first
- 1.
a ??= bisa ?? (a = b): the assignment is inside the short circuit, not outside it. - 2.
&&=only assigns when the current value is truthy, so it updates what is there and never creates what is missing. - 3. To see whether a write happened, give the object a setter that counts.
const applyDefaults = (o) => {
o.pageSize ??= 20; // absent only
o.label ||= 'Ikeja stall'; // anything falsy
o.currency ??= 'NGN';
o.note &&= o.note.trim(); // present only
return o;
};
const partial = applyDefaults({ pageSize: 0, label: '', note: ' ripe ' });
const empty = applyDefaults({});
const noteWasNotCreated = 'note' in empty;
let writes = 0;
let reads = 0;
const account = {
_kobo: 500000,
get kobo() {
reads++;
return this._kobo;
},
set kobo(value) {
writes++;
this._kobo = value;
},
};
account.kobo ??= 1; // 500000 is not nullish, so NO write
account.kobo ||= 1; // 500000 is truthy, so NO write
const writesAfterShortCircuit = writes;
account.kobo &&= account.kobo + 100; // truthy, so this one does write
const writesAfterUpdate = writes;
const always = { _n: 0, get n() { return this._n; }, set n(v) { writes++; this._n = v; } };
always.n = always.n || 7; // the old spelling: always writes
const writesAfterOldSpelling = writes;
const flags = { verbose: false, retries: 0 };
flags.verbose ||= true;
flags.retries ??= 5;
console.log('partial:', partial);
console.log('empty :', empty, '| note created:', noteWasNotCreated);
console.log('account:', account._kobo, '| writes:', writes, '| reads:', reads);
console.log('flags :', flags);
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.
test('??= keeps a real 0, ||= replaces an empty string', [partial.pageSize, partial.label], [0, 'Ikeja stall']);
test('&&= updates a value that is already there', partial.note, 'ripe');
test('and fills in what was absent', [empty.pageSize, empty.label, empty.currency], [20, 'Ikeja stall', 'NGN']);
test('but &&= on a missing key does not even create it', noteWasNotCreated, false);
test('a short-circuited ??= or ||= performs no assignment at all', writesAfterShortCircuit, 0);
test('&&= on a truthy value does assign', [writesAfterUpdate, account._kobo], [1, 500100]);
test('while x = x || y writes every time, setter and all', [writesAfterOldSpelling, always._n], [2, 7]);
test('so ||= clobbers false and ??= respects 0, which is usually backwards from what you want', [flags.verbose, flags.retries], [true, 0]);
The three logical assignments are short-circuiting, and the short circuit covers the assignment. a ||= b is a || (a = b), not a = a || b. With a plain data property you cannot tell the difference; with a setter, a Proxy, a reactive store or a DOM property you certainly can, because the older spelling fires the setter every single time and the newer one only fires it when the value actually changes.
Pick by the question you are asking. ??= means "if it was never supplied". ||= means "if it is empty or zero or false". &&= means "if there is something here, transform it", which is the neat way to trim, round or normalise an optional field without an if.
The last assertion is the whole trap in one line: flags.verbose ||= true flips a deliberate false to true, because false is falsy and ||= cannot tell a chosen false from a missing one. For booleans and numbers, ??= is almost always the one you meant.