JavaScriptOperatorsAlgorithmsBigInt

JavaScript Remainder Operator: %, Negative Numbers, and Modulo

JavaScript % returns remainder, not mathematical modulo. Learn negative results, non-negative normalization, odd/even checks, circular indexes, angles, BigInt, and floating-point limits.

·Updated ·7 min read·Counting...
JavaScript Remainder Operator: %, Negative Numbers, and Modulo

JavaScript's % operator returns the remainder. It is not a mathematical modulo operator that always returns a non-negative result. The result usually follows the sign of the dividend, so -1 % 5 is -1, not 4.

Basic behavior

12 % 5  // 2
10 % 2  // 0
7 % 3   // 1
-7 % 3  // -1
7 % -3  // 1

With Number values, division by zero returns NaN:

10 % 0 // NaN

Non-negative modulo

Circular indexes, weekdays, and angles often need a result in [0, n):

function modulo(value, divisor) {
  return ((value % divisor) + divisor) % divisor
}

modulo(-1, 5) // 4
modulo(6, 5)  // 1

Before calling this helper, make sure divisor is a non-zero finite number that matches your business rule.

Odd and even checks

function isEven(value) {
  return value % 2 === 0
}

For user input, validate integer-ness first:

function isEvenInteger(value) {
  return Number.isInteger(value) && value % 2 === 0
}

Circular indexes

function nextIndex(current, length) {
  if (length <= 0) throw new Error("length must be positive")
  return (current + 1) % length
}

function previousIndex(current, length) {
  if (length <= 0) throw new Error("length must be positive")
  return modulo(current - 1, length)
}

Moving forward does not produce a negative number. Moving backward can, so use the modulo helper.

Angle normalization

function normalizeDegrees(degrees) {
  return modulo(degrees, 360)
}

normalizeDegrees(450) // 90
normalizeDegrees(-90) // 270

For animation, normalization only solves the range. You may still need to handle interpolation direction from 359 to 0.

BigInt

BigInt also supports remainder, but both sides must be BigInt:

10n % 3n // 1n

This throws:

10n % 3

BigInt division by 0n throws an error instead of returning NaN.

Floating-point caution

0.3 % 0.1

may not produce an exact zero because of binary floating-point representation. For money or exact decimal steps, convert to the smallest integer unit or use an appropriate decimal strategy.

Subscribe to FreeMac

Weekly picks: free Mac software reviews, trusted source updates, alternatives, and low-friction guides.