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 OR assignment (||=) operator evaluates the left operand and assigns the right operand to the left operand only if the left operand is falsy.
x ||= y

Mechanics and Short-Circuit Evaluation

The operator relies on short-circuit evaluation. When the JavaScript engine encounters x ||= y, it performs the following steps:
  1. Evaluates the left-hand side (LHS) operand.
  2. Coerces the LHS value to a boolean.
  3. If the LHS is truthy, the operation short-circuits. The right-hand side (RHS) is never evaluated, and no assignment takes place.
  4. If the LHS is falsy, the engine evaluates the RHS and assigns its resulting value to the LHS.
In JavaScript, the following values are falsy and will trigger the assignment: false, 0, -0, 0n, "" (empty string), null, undefined, and NaN.

Logical Equivalence

The ||= operator is strictly equivalent to the following logical expression:
x || (x = y)
It is a common misconception that x ||= y is equivalent to x = x || y. While the resulting value is often the same, the underlying mechanics differ significantly. The expression x = x || y always performs an assignment operation, whereas x ||= y conditionally performs the assignment.

Syntax Visualization

let a = 0;      // 0 is falsy
a ||= 10;       // RHS is evaluated and assigned
console.log(a); // 10

let b = 42;     // 42 is truthy
b ||= 10;       // Short-circuits; RHS is ignored, no assignment occurs
console.log(b); // 42

let c = "";     // Empty string is falsy
c ||= "text";   // RHS is evaluated and assigned
console.log(c); // "text"

Impact on Object Setters

Because ||= only performs an assignment if the LHS is falsy, it prevents unnecessary setter invocations on objects. This is the primary technical distinction between ||= and standard assignment combined with a logical OR.
const obj = {
  _value: 100,
  get value() {
    return this._value;
  },
  set value(val) {
    console.log("Setter invoked!");
    this._value = val;
  }
};

// obj.value evaluates to 100 (truthy).
// The operation short-circuits. The setter is NEVER invoked.
obj.value ||= 200; 

// Contrast with standard assignment:
// The setter IS invoked here, even though the value remains 100.
obj.value = obj.value || 200; 
Master JavaScript with Deep Grasping Methodology!Learn More