Emmanuel Akinfulubi

JavaScriptMath

Modulo of negative numbers in JavaScript

Intermediate · 4 min read

The % operator looks simple: 7 % 3 is 1, because 3 goes into 7 twice with 1 left over. Then you try a negative number, and the answer surprises you. -7 % 3 is not 2, as a maths textbook would say. In JavaScript it is -1.

That difference causes real bugs. A carousel that should wrap from the first slide back to the last one breaks. An "is this number odd?" check says no for -7. In this tutorial you will test % with every combination of signs, find out which number decides the sign of the answer, and see exactly where those two bugs come from. You only need to know what % and Math.trunc do.

Remainder or modulo?

Two ideas get mixed up here:

  • A remainder is what is left over after a division. JavaScript's % gives a remainder.
  • A modulo is the maths idea used for clocks and cycles. Its answer is never negative when you divide by a positive number. On a 3-hour clock, -7 lands on 2.

For positive numbers, the two always agree. They only part ways when a negative number is involved. JavaScript, C, Java and Go use the remainder rule. Python and Ruby use the modulo rule, so -7 % 3 is 2 in Python. Neither language is wrong, but code copied from one to the other can change behavior without any error.

Here is the exercise. Try it yourself first if you like, then read on and we will build it together.

23 The sign of % on negatives

fair

Evaluate -7 % 3, 7 % -3 and -7 % -3. Which operand decides the sign? Then show % is not the mathematical modulo.

Stuck? Three hints, smallest first
  1. 1. The result takes the sign of the dividend, the left-hand operand.
  2. 2. It is defined as a - trunc(a / b) * b, so it follows truncating division.
  3. 3. Mathematically, -7 mod 3 is 2. JavaScript gives -1.

Step 1: start with positives

Step 1

console.log(7 % 3); // 1

3 goes into 7 twice (6), with 1 left over. Nothing surprising yet.

Step 2: flip the signs one at a time

Step 2

console.log(-7 % 3);  // -1
console.log(7 % -3);  // 1
console.log(-7 % -3); // -1

Look at which results are negative: the first and the third. Those are the two where the dividend, the number on the left, is negative. The sign of the divisor on the right makes no difference at all.

So the rule is short: the answer of % takes the sign of the left-hand number.

Step 3: where the rule comes from

JavaScript defines a % b as a - Math.trunc(a / b) * b. You can write that out and check it gives the same answer:

Step 3

console.log(Math.trunc(-7 / 3));             // -2
console.log(-7 - Math.trunc(-7 / 3) * 3);    // -1

-7 / 3 is about -2.33. Math.trunc cuts toward zero, giving -2. Then -7 minus (-2 times 3) is -7 + 6, which is -1. The remainder follows a division that cuts toward zero, and that is what makes it negative.

Step 4: fractions work too

% isn't only for whole numbers:

Step 4

console.log(5.5 % 2); // 1.5

2 goes into 5.5 twice (4), leaving 1.5. This is handy for things like wrapping an angle or a time of day that has a decimal part.

Step 5: bug one, wrapping an index backwards

Say you have 5 slides, numbered 0 to 4, and the user presses "previous" on slide 0. You want slide 4. A natural first attempt is (i - 1) % 5:

Step 5

const i = 0;
console.log((i - 1) % 5); // -1, not 4

-1 % 5 keeps the minus sign, so you get -1, and an array has nothing at index -1 (slides[-1] is undefined). The next exercise builds a small helper that gives 4 here.

Step 6: bug two, checking for odd numbers

Another common line is n % 2 === 1 to test for odd numbers:

Step 6

console.log(7 % 2);  // 1
console.log(-7 % 2); // -1
console.log(-7 % 2 === 1); // false, but -7 is odd

For any negative odd number the remainder is -1, so the check fails. The fix is to compare against zero instead: n % 2 !== 0 is true for 7 and -7 alike.

The full solution

The answer panel prints all four sign combinations, the definition with Math.trunc, the fraction case and the backwards wrap. The checks underneath confirm that the sign comes from the dividend, that -7 % 3 is not 2, and that a parity check must compare with 0. Press Run to see the output.

The answer

console.log('7 % 3    :', 7 % 3);
console.log('-7 % 3   :', -7 % 3, '<- sign of the dividend');
console.log('7 % -3   :', 7 % -3, '<- divisor sign ignored');
console.log('-7 % -3  :', -7 % -3);
console.log('by definition:', -7 - Math.trunc(-7 / 3) * 3);
console.log('5.5 % 2  :', 5.5 % 2, '<- fractions are allowed');
console.log('wrapping an index backwards:', -1 % 5, '<- not 4');

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('a positive remainder is unsurprising', 7 % 3, 1);
test('the sign comes from the dividend', -7 % 3, -1);
test('not from the divisor', 7 % -3, 1);
test('both negative still gives a negative', -7 % -3, -1);
test('so % is not the mathematical modulo', -7 % 3 === 2, false);
test('it is the remainder of a truncating division', -7 - Math.trunc(-7 / 3) * 3, -1);
test('the operands may be fractional', 5.5 % 2, 1.5);
test('wrapping an index backwards therefore fails', -1 % 5, -1);
test('and a parity check must compare to 0, never to 1', [-7 % 2, 7 % 2], [-1, 1]);

% in JavaScript, C, Java and Go is a remainder operator, not a modulo operator. Python and Ruby give 2 for -7 % 3; JavaScript gives -1. Both are internally consistent — they pair with different definitions of integer division — and neither is wrong, but code ported between them silently changes behaviour.

Two places this bites. Wrapping an index: (i - 1) % n gives -1 at the start of the array rather than the last element. And parity: n % 2 === 1 is false for every negative odd number, so use n % 2 !== 0. Exercise 24 builds the helper that fixes the first.

Common mistakes

  • Thinking % is the maths modulo. It is a remainder. With a negative dividend, the answer is negative.
  • Wrapping an index with (i - 1) % n. At the start of the list it gives -1. Use a true modulo helper instead.
  • Testing odd numbers with n % 2 === 1. It is false for every negative odd number. Write n % 2 !== 0.

Try it yourself

  1. Predict -10 % 4, 10 % -4 and -10 % -4 before you run them.
  2. Check the definition a - Math.trunc(a / b) * b against % for a = -13 and b = 5.
  3. Write isOdd(n) using n % 2 !== 0 and test it on 3, -3, 4 and 0.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.