Skip to main content
The <<= (Left Shift Assignment) operator performs a bitwise left shift on its left operand by the number of bits specified by its right operand, and assigns the computed result back to the left operand.

Execution Mechanics

When evaluating x <<= y, TypeScript (inheriting from JavaScript’s ECMAScript specification) processes the operation based on the underlying types of the operands.

For number Types

  1. Type Conversion (ToInt32): Both x and y are implicitly coerced into 32-bit signed integers using two’s complement representation. Any fractional components are discarded.
  2. Shift Masking: The right operand y is masked to 5 bits using a bitwise AND operation (y & 0x1F). Consequently, the actual shift amount is strictly between 0 and 31. This is fundamentally different from the remainder operator (%), as negative shift amounts are safely masked to positive values (e.g., -1 & 0x1F evaluates to 31, whereas -1 % 32 evaluates to -1).
  3. Bit Manipulation: The bits of x are shifted to the left by the evaluated shift amount.
  4. Zero-Filling: Vacated bit positions on the right are filled with 0s.
  5. Truncation: Any bits shifted beyond the 32-bit boundary on the left are permanently discarded.
  6. Sign Mutation: Because the 32nd bit (Most Significant Bit) dictates the sign in two’s complement, shifting a 1 into this position will mutate a positive integer into a negative integer.

For bigint Types

When both operands are of type bigint, the operator behaves differently:
  1. Arbitrary Precision: The left operand is treated as an integer of arbitrary size. It is not truncated to 32 bits.
  2. No Shift Masking: The right operand is not masked to 5 bits. You can shift by amounts greater than 31.
  3. Negative Shift Amounts: Unlike number types, shifting a bigint by a negative amount is an invalid operation. Attempting to do so (e.g., bigX <<= -1n) will throw a runtime RangeError (“Right-hand side of ‘shift left’ operation must be non-negative”).
  4. Type Strictness: TypeScript enforces that both operands must be bigint. Mixing number and bigint with <<= will result in a compiler error (TS2365).

Mathematical Equivalence

For number types, assuming no 32-bit overflow occurs, x <<= y is mathematically equivalent to: x = x * (2 ** y)
Tired of Poor TypeScript Skills? Fix That With Deep Grasping!Learn More