Skip to main content
The ^= (bitwise XOR assignment) operator performs a bitwise exclusive OR operation on the binary representations of its left and right operands, assigning the computed result back to the left operand.
While conceptually similar to the expanded assignment syntax (leftOperand = leftOperand ^ rightOperand), the ^= operator evaluates the leftOperand exactly once. This is a critical distinction when the left operand contains expressions with side effects. For example, arr[i++] ^= 2 increments i only once, whereas arr[i++] = arr[i++] ^ 2 would evaluate the index and increment i twice.

Execution Mechanics

When the ^= operator is invoked, the TypeScript runtime (via JavaScript) executes the following sequence based on the operand types:
  1. Numeric Conversion & Truncation:
    • For number operands: Both operands are evaluated and implicitly converted to 32-bit signed integers using two’s complement representation. Any fractional components are truncated.
    • For bigint operands: Both operands are evaluated at arbitrary precision without being truncated to 32 bits.
  2. Bitwise Comparison: The operator compares the operands bit by bit. It yields a 1 in a given bit position if the corresponding bits of the operands differ, and a 0 if they are identical.
    • 0 ^ 0 = 0
    • 0 ^ 1 = 1
    • 1 ^ 0 = 1
    • 1 ^ 1 = 0
  3. Assignment: The newly constructed numeric value (either a 32-bit integer or a bigint) is assigned to the memory location of the leftOperand.

Step-by-Step Evaluation

Binary Breakdown:
  • a (5) is represented as ...0000 0101
  • b (3) is represented as ...0000 0011

TypeScript Compiler Rules

TypeScript enforces strict type checking on bitwise assignment operators to prevent unintended runtime coercions.
  • Valid Assignment Targets: The left operand must be a valid assignment target (l-value). This includes standalone variables, object properties, and array elements.
  • Left Operand Type Constraints: The left operand must resolve to type number, bigint, or any. In modern TypeScript (5.0+), an enum variable is not a valid left operand for ^=. While the bitwise XOR operation itself accepts enums, it evaluates to a number. This resulting number cannot be implicitly assigned back to an enum type.
  • Operand Mixing Rules:
    • number and bigint types are strictly incompatible and cannot be mixed in the same operation.
    • enum members are treated as numeric values and can be used as the right operand when the left operand is a number.
    • any bypasses all strict type matching constraints, allowing operations with any right operand (though standard JavaScript runtime coercion rules will apply).
Tired of Poor TypeScript Skills? Fix That With Deep Grasping!Learn More