Skip to main content
The %= (remainder assignment) operator divides the value of the left operand (dividend) by the value of the right operand (divisor) and assigns the resulting remainder to the left operand. As a compound assignment operator, it evaluates the left-hand side reference only once, distinguishing it from a standard assignment combined with a modulo operation.

Mechanics

  1. Evaluation: The left operand is evaluated first to resolve its reference and retrieve its value. Then, the right operand is evaluated.
  2. Calculation: The JavaScript engine performs a truncated division (rounding towards zero) of the left operand’s value by the right operand’s value to determine the remainder.
  3. Sign Preservation: The sign of the returned remainder strictly matches the sign of the dividend (the left operand), regardless of the sign of the divisor.
  4. Assignment: The computed remainder is written back to the resolved memory location of the left operand.

TypeScript Type Constraints

TypeScript enforces strict type checking on the %= operator:
  • Valid Types: Both operands must resolve to number or bigint.
  • Type Homogeneity: You cannot mix number and bigint operands. Doing so results in a ts(2365) compiler error.
  • Mutability: The left operand must be a valid l-value (a mutable reference, such as a variable declared with let or a writable object property). It cannot be a const.

Syntax and Behavior Examples

Standard Numeric Evaluation:
Sign Preservation (Negative Dividend):
Single Evaluation of Left Operand: Because the left operand is evaluated only once, %= behaves differently than x = x % y when the left operand contains side effects.
BigInt Evaluation:
TypeScript Compiler Errors:

Edge Cases (IEEE 754 Floating Point)

Because TypeScript number types are double-precision 64-bit floats, the operator handles specific edge cases according to the IEEE 754 standard:
  • If the dividend is Infinity or -Infinity, the result is NaN.
  • If the divisor is 0 or -0, the result is NaN.
  • If the dividend is 0 and the divisor is non-zero, the result is 0.
Tired of Poor TypeScript Skills? Fix That With Deep Grasping!Learn More