Glossary / Logical assignment
Logical assignment
Logical assignment operators combine short-circuit logic with assignment. &&=, ||=, and ??= conditionally assign to a variable or property using truthiness or nullishness. They can express concise initialization, but their semantics differ and they may invoke getters or setters on the left-hand reference.
Three operators
let retries = 0;
retries ||= 3; // 3: zero is falsy, so it is replaced
let pageSize = 0;
pageSize ??= 25; // remains 0: it is not nullish
let enabled = true;
enabled &&= checkPermission(); // invokes checkPermission because enabled is truthy
x &&= y: assignyifxis truthy; otherwise preserve x.x ||= y: assignyifxis falsy.x ??= y: assignyif x is null or undefined.
The right-hand side is evaluated only when assignment occurs. The left-hand reference is evaluated once, which matters for computed properties or accessors. Assignment can trigger a setter, and a getter may be used to decide whether the right side runs. Choose the operator based on the domain’s absent/default rule; using ||= for counts or flags can erase meaningful zero/false values.
Interview questions
- Which operator preserves zero and false?
??=. - When does
||=assign? When the current value is falsy. - Is the right side always evaluated? No, these are short-circuit operators.
- Can logical assignment trigger accessor behavior? Yes; reading and assigning a property can invoke getters/setters.