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 strictly if the left operand is falsy. It leverages short-circuit evaluation to prevent both unnecessary assignments and the evaluation of the right operand when the left operand is truthy.
x ||= y

Logical Equivalence

The operation x ||= y is logically equivalent to:
x || (x = y)
It is a common misconception that x ||= y is identical to x = x || y. The ||= operator guarantees that no assignment occurs if x is truthy. This distinction is critical when the left operand is a property with a setter; ||= will not trigger the setter unless the underlying value is falsy, whereas x = x || y triggers the setter unconditionally.

Falsy Evaluation

The assignment is executed if and only if the left operand evaluates to one of the following JavaScript falsy values:
  • false
  • 0 or -0
  • 0n (BigInt zero)
  • "" (empty string)
  • null
  • undefined
  • NaN

TypeScript Type Constraints

In TypeScript, the type of the right operand must be assignable to the type of the left operand. Because the operator handles falsy values, the left operand’s type typically includes a union of a truthy type and a falsy type (like null, undefined, or 0).
let value: string | undefined = undefined;
let fallback: string = "default";

// Valid: 'fallback' (string) is assignable to 'value' (string | undefined)
value ||= fallback; 
If the right operand’s type is not assignable to the left operand’s declared type, TypeScript will emit a type error (TS2322), even if the operation is valid at runtime.
let count: number = 0;

// Error TS2322: Type 'string' is not assignable to type 'number'.
count ||= "invalid"; 

Evaluation Order

  1. The left operand is evaluated.
  2. The left operand is coerced to a boolean.
  3. If the boolean evaluates to true (truthy), the operation short-circuits, returning the left operand’s value.
  4. If the boolean evaluates to false (falsy), the right operand is evaluated.
  5. The result of the right operand is assigned to the left operand, and that value is returned.
Master TypeScript with Deep Grasping Methodology!Learn More