Course contentsShow
← JavaScript
Lesson 1960 of 2,72341. Modern JavaScript Features (ES2020+)Free lesson

Short-Circuit Evaluation Behavior

How logical assignment operators short-circuit and only perform assignment when the condition requires it.

Short-Circuit Evaluation Behavior

What you'll learn: How logical assignment operators short-circuit and only perform assignment when the condition requires it.

The Core Principle

Logical assignment operators (||=, &&=, ??=) don't just use short-circuit evaluation—they are short-circuit assignments. The assignment itself only happens if the logical condition requires it. This is fundamentally different from regular assignment operators.

Think of it like a conditional gate: the operator first checks whether assignment is necessary, and only crosses the threshold to actually assign when the logic demands it.

How It Works

With ||=, assignment only occurs if the left side is falsy:

let count = 5;
count ||= 10;  // No assignment happens! count is truthy
console.log(count);  // 5

With &&=, assignment only occurs if the left side is truthy:

let user = { name: "Alice" };
user.settings &&= { theme: "dark" };  // Assignment happens
console.log(user.settings);  // { theme: "dark" }

user = null;
user.settings &&= { theme: "dark" };  // No assignment! user is falsy

With ??=, assignment only occurs if the left side is nullish:

let value = 0;
value ??= 100;  // No assignment! 0 is not nullish
console.log(value);  // 0

Why This Matters

Short-circuiting means the right-hand expression isn't even evaluated if assignment won't happen. This prevents unnecessary computations and side effects:

let config = { existing: true };
config.data ??= expensiveFunction();  // expensiveFunction never called

Key Takeaway: Logical assignment operators perform the assignment only when their logical condition requires it, making them both efficient and semantically precise for conditional initialization patterns.