Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The logical AND assignment (&&=) operator assigns the value of its right operand to its left operand only if the left operand evaluates to a truthy value. It combines logical AND (&&) short-circuiting evaluation with variable assignment.

Syntax

leftExpr &&= rightExpr

Mechanical Equivalence

The &&= operator is logically equivalent to the following expression:
leftExpr && (leftExpr = rightExpr);
It is a common misconception to equate x &&= y with x = x && y. While the resulting value is often the same, the underlying execution differs significantly due to short-circuiting:
  • In x = x && y, the assignment operation always occurs, regardless of whether x is truthy or falsy.
  • In x &&= y, if x is falsy, the assignment operation is entirely skipped. This prevents unnecessary setter invocations and avoids triggering side effects associated with property assignment.

Evaluation Rules

  1. The JavaScript engine evaluates leftExpr.
  2. It determines the boolean coercion (truthiness) of the evaluated leftExpr.
  3. If leftExpr is truthy: The engine evaluates rightExpr and assigns the resulting value to leftExpr.
  4. If leftExpr is falsy: The engine short-circuits. rightExpr is never evaluated, no assignment takes place, and leftExpr retains its original value.
(Note: Falsy values in JavaScript are false, 0, -0, 0n, "", null, undefined, and NaN. All other values are truthy.)

Code Visualization

Truthy Evaluation (Assignment Occurs):
let x = 5;      // 5 is truthy
x &&= 10;       // x is truthy, so 10 is assigned to x
console.log(x); // 10
Falsy Evaluation (Short-Circuiting):
let y = 0;      // 0 is falsy
y &&= 10;       // y is falsy, assignment is skipped
console.log(y); // 0
Proof of Short-Circuiting:
let z = null;

// The function on the right is never invoked because 'z' is falsy.
z &&= (function() {
    console.log("Right operand evaluated");
    return "new value";
})();

console.log(z); // null

Return Value

The &&= expression returns the final value of leftExpr after the operation completes. If an assignment occurred, it returns the value of rightExpr. If it short-circuited, it returns the original falsy value of leftExpr.
Master JavaScript with Deep Grasping Methodology!Learn More