JavaScript Logical Assignment: ||=, &&= and ??=
Quick answer
Logical assignment combines a test with conditional assignment. It avoids writing a value when the existing value already satisfies the relevant condition.
How it works
x ||= value writes only for falsy x; x &&= value writes only for truthy x; x ??= value writes only for nullish x. The left-hand reference is evaluated once and the right operand only when needed. For property access this matters when getters or computed keys have side effects.
let count = 0;count ??= 5;console.log(count);count ||= 5;console.log(count);Expected output in Node.js:
05Zero is falsy but not nullish.
let active = false;let calls = 0;active &&= ++calls;console.log(active, calls);Expected output in Node.js:
false 0The right side is skipped for a falsy left side.
Common mistakes
Choose ??= for a default that preserves 0, false and empty text. ||= would replace these values.
Practice
Choose an operator to fill a missing counter without replacing zero.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Logical Assignment: ||=, &&= and ??= — Knowledge Check
Apply the taught concept and predict the output.
Which logical assignment preserves an existing empty string when supplying a missing-value default?
When is the right operand of &&= evaluated?
How often is the left-hand reference evaluated by logical assignment?
What is the exact console output in JavaScript Logical Assignment: ||=, &&= and ??= example 1?
let count = 0;count ??= 5;console.log(count);count ||= 5;console.log(count);What is the exact console output in JavaScript Logical Assignment: ||=, &&= and ??= example 2?
let active = false;let calls = 0;active &&= ++calls;console.log(active, calls);