Sub topic 16
Compound and Logical Assignment
This chapter assumes you know how ||, &&, and ?? short-circuit, and which values count as falsy versus nullish. Both topics were covered in earlier chapters. Here we look at how assignment builds on those operators. That includes some behavior that is easy to miss: what the assignment expression returns, how many times the target is evaluated, and when logical assignment skips the write completely.
Plain assignment is an expression
The = operator stores a value and also produces that value as its result. That is why assignment can appear inside a larger expression. Assignment is right-associative, so a chain of assignments groups from the right.
let a;
let b;
console.log(a = 5); // 5: the expression evaluates to the assigned value
a = b = 3; // parsed as a = (b = 3)
console.log(a, b); // 3 3
const total = 10;
try {
total = 11; // reassigning a const binding
} catch (e) {
console.log(e instanceof TypeError); // true
}Assignment sits near the bottom of the precedence table. Only the comma operator, yield, arrow functions, and spread rank lower. In x = y + 1 || 2, the whole right side is evaluated before the result is stored.
Compound assignment
A compound assignment operator merges a binary operator with =. The expression x op= y is roughly x = x op y. The operand rules are the same as for the plain operator, so += concatenates when either side becomes a string after ToPrimitive.
| Operator | Equivalent (roughly) | Notes | Column |
|---|---|---|---|
| `x += y` | `x = x + y` | Adds numbers, concatenates strings | |
| `x -= y`, `x *= y`, `x /= y`, `x %= y` | `x = x - y`, and so on | Always numeric (or BigInt) | |
| `x **= y` | `x = x ** y` | Exponentiation | |
| `x <<= y`, `x >>= y`, `x >>>= y` | `x = x << y`, and so on | 32-bit integer shifts | |
| `x &= y`, `x \ | = y`, `x ^= y` | `x = x & y`, and so on | 32-bit bitwise |
let count = 5;
count += 2; // 7
count **= 2; // 49
count %= 10; // 9
let label = 'Item ';
label += 3; // 'Item 3': string concatenation
let n = '4';
n -= 1; // 3: - always converts to a number
console.log(count, label, n); // 9 'Item 3' 3The target is evaluated only once
The word "roughly" in the table matters. In x op= y, the reference x is resolved once, and that single reference is used for both the read and the write. If finding the target has side effects, such as a function call inside a computed key, the compound form and the long form behave differently.
let calls = 0;
const counts = { a: 0 };
function key() {
calls++;
return 'a';
}
counts[key()] += 1;
console.log(counts.a, calls); // 1 1: key() ran once
counts[key()] = counts[key()] + 1;
console.log(counts.a, calls); // 2 3: key() ran twice moreThis is a correctness issue as well as a performance one. If key() returned a different value on each call, the long form would read one property and write another.
Logical assignment
ES2021 added three logical assignment operators, ||=, &&=, and ??=. Each one keeps the falsy-versus-nullish distinction of its underlying operator.
| Operator | Assigns when the current value is | Precise meaning | Column | Column | Column | Column |
|---|---|---|---|---|---|---|
| `x \ | \ | = y` | falsy | `x \ | \ | (x = y)` |
| `x &&= y` | truthy | `x && (x = y)` | ||||
| `x ??= y` | `null` or `undefined` | `x ?? (x = y)` |
const opts = { retries: 0, name: '', timeout: null, title: ' Report ' };
opts.retries ||= 3; // 3: 0 is falsy, so it is replaced
opts.name ??= 'anon'; // '': '' is not nullish, so it is kept
opts.timeout ??= 5000; // 5000: null is nullish
opts.title &&= opts.title.trim(); // 'Report': runs only if title is truthy
console.log(opts);
// { retries: 3, name: '', timeout: 5000, title: 'Report' }The same choice from earlier chapters applies here. ||= overwrites legitimate values such as 0, '', false, and NaN. Use ??= when those values are valid settings.
Short-circuiting skips the write
x ||= y is not the same as x = x || y. The long form always assigns, even when it writes back the value that was already there. The logical assignment operators write only when the condition allows it. When they short-circuit, the right side is never evaluated and no store happens. Setters show the difference:
const config = {
_level: 'info',
get level() { console.log('get'); return this._level; },
set level(v) { console.log('set', v); this._level = v; },
};
config.level ||= 'debug'; // logs: get
config.level = config.level || 'debug'; // logs: get, then set infoThe skipped write also matters for read-only properties. In strict mode, assigning to a frozen object's property throws. A logical assignment that short-circuits does not assign, so it does not throw:
'use strict';
const frozen = Object.freeze({ x: 1, y: 0 });
frozen.x ||= 2; // no error: x is truthy, so nothing is written
try {
frozen.y ||= 2; // y is falsy, so a write is attempted
} catch (e) {
console.log(e instanceof TypeError); // true
}Lazy initialization
Because the right side runs only when needed, ??= works well for caches and lazy defaults:
const cache = {};
let computeCalls = 0;
function compute(k) {
computeCalls++;
return k.toUpperCase();
}
function lookup(k) {
return (cache[k] ??= compute(k)); // result is the stored value
}
lookup('a');
lookup('a');
lookup('b');
console.log(cache, computeCalls); // { a: 'A', b: 'B' } 2Common errors
- Using
||=for numeric or boolean settings and silently replacing0orfalse. - Assuming
x ||= f()always callsf. It callsfonly whenxis falsy. - Combining
+=with values that might be strings, which gives'5' + 1 === '51'instead of6. - Expanding
obj[expr()] += 1by hand into the long form and changing how many timesexpr()runs.
Exercise
Given const s = { count: 0, tag: null, on: false };, what does s contain after running s.count ||= 10; s.tag ??= 'new'; s.on &&= 'yes'; s.count += '1';?
Show answer
{ count: '101', tag: 'new', on: false }. count is 0, which is falsy, so ||= sets it to 10. tag is null, so ??= assigns 'new'. on is false, so &&= short-circuits and leaves it unchanged. Finally 10 += '1' concatenates, because one operand is a string, producing '101'.
Exercise
An object has a setter on level that logs every write. Its current value is 'warn'. How many times does the setter run for obj.level ??= 'info', and how many times for obj.level = obj.level ?? 'info'?
Show answer
Zero times for ??=, because 'warn' is not nullish, so the operator short-circuits and does not write. Once for the long form, because plain assignment always performs the write, even though it stores the same value 'warn'.
Exercise
Why does let i = 0; const arr = [10, 20]; arr[i++] += 5; leave arr as [15, 20] and i as 1, instead of reading one element and writing another?
Show answer
Compound assignment evaluates the target reference arr[i++] once. i++ produces index 0 and then increments i to 1. That single reference to arr[0] is used for both the read (10) and the write (15). The hand-written form arr[i++] = arr[i++] + 5 would evaluate i++ twice, writing arr[0] = arr[1] + 5.