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

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

  1. Which operator preserves zero and false? ??=.
  2. When does ||= assign? When the current value is falsy.
  3. Is the right side always evaluated? No, these are short-circuit operators.
  4. Can logical assignment trigger accessor behavior? Yes; reading and assigning a property can invoke getters/setters.

References