Remainder (%) vs modulo for every sign in JavaScript
Beginner · 4 min read
Clocks wrap from 12 back to 1. A carousel wraps from the last slide back to the first. A game map wraps from the right edge to the left. All of these need a number that "wraps around" inside a fixed range, and most people reach for % to do it. That works until a number goes negative.
In this tutorial you will see what % really gives for every mix of positive and negative numbers, then write a small mod(a, n) function that always lands between 0 and n - 1. You will finish by answering a clock question: what hour is three hours before one o'clock? You need to know arrow functions and basic division.
What % actually does
% is called the remainder operator. It divides, keeps the whole part of the answer cut toward zero, and gives you what is left over.
console.log(7 % 3); // 1: 7 is 3 * 2 + 1
console.log(-7 % 3); // -1: -7 is 3 * -2 + -1
The key rule: the answer takes the sign of the number on the left. So -7 % 3 is -1, not 2.
Remainder versus modulo
In math, modulo means "where do you land on a loop of size n?". On a loop of 3, stepping back 7 from 0 lands you on 2, never on -1. A true modulo is never negative when n is positive. JavaScript has no modulo operator, only the remainder. For positive numbers the two agree, which is why the difference catches people out.
Here is the exercise. Try it on your own first if you like, then read on and we will build it together.
81 Per cent is a remainder, not a modulo
easyWork out what % gives for every sign combination of 7 and 3, then write a mod(a, n) that always lands in the range 0 to n - 1. Use it to answer a clock question: what hour is three hours before one o'clock?
Stuck? Three hints, smallest first
- 1. The result of
a % ntakes the sign ofa, never ofn. - 2. Adding
nonce and taking%again fixes a single negative remainder. - 3. Also check
7 % 0and-6 % 3. Neither does what the name suggests.
Step 1: every sign combination
Start by asking % about all four sign mixes of 7 and 3.
const remainder = (a, n) => a % n;
console.log(remainder(7, 3), remainder(-7, 3)); // 1 -1
console.log(remainder(7, -3), remainder(-7, -3)); // 1 -1
Flipping the sign of the right-hand number changes nothing. Only the left-hand number decides the sign of the answer.
Step 2: the odd cases
A few inputs behave in ways the name doesn't suggest.
console.log(-6 % 3, Object.is(-6 % 3, -0)); // -0 true
console.log(5.5 % 2); // 1.5
console.log(7 % 0); // NaN
console.log(Infinity % 3, 3 % Infinity); // NaN 3
-6 % 3 is minus zero, a special value that compares equal to 0 with ===. Object.is is a stricter comparison that can tell the two apart. Node shows it as -0, but turning it into text gives "0", so it usually hides.
% also works on decimals: 5.5 is 2 * 2 + 1.5. And dividing by zero does not throw an error. It gives NaN ("not a number"), which then spreads into every later sum.
Step 3: the wrong turn
Say you want to step backward through a list of 3 items with i % 3:
const items = ['a', 'b', 'c'];
console.log(items[-1 % 3]); // undefined
-1 % 3 is -1, and an array has nothing at index -1. No error, just a silent undefined. This is the bug a real modulo fixes.
Step 4: a true modulo with two % calls
The fix is a short formula: take the remainder, add n, then take the remainder again.
const mod = (a, n) => ((a % n) + n) % n;
console.log(mod(-7, 3), -7 % 3); // 2 -1
console.log(mod(-1, 12)); // 11
console.log(mod(-13, 5)); // 2
Here is why it works. a % n is somewhere between -(n - 1) and n - 1. Adding n moves it into the range 1 to 2n - 1, which is never negative. The second % n brings it back down into 0 to n - 1.
The second % is not extra. Without it, mod(7, 3) would be 1 + 3 = 4, which is outside the range.
It also cleans up minus zero:
console.log(Object.is(mod(-6, 3), 0)); // true
Step 5: the clock question
A twelve-hour clock has no hour 0. Hour 0 is really 12. So use mod with 12, and swap a 0 for 12.
const hoursBefore = (hour, back) => mod(hour - back, 12) || 12;
console.log(hoursBefore(1, 3)); // 10
console.log(hoursBefore(3, 3)); // 12
console.log(hoursBefore(12, 25)); // 11
|| gives back the right side when the left side is "falsy", and 0 is falsy. So a result of 0 becomes 12, and any other hour passes through unchanged. Three hours before one o'clock is ten o'clock, and 25 hours before 12 is 11, because the clock wraps twice on the way.
The full solution
The answer panel has remainder, mod and hoursBefore, and prints all four sign mixes, minus zero, the decimal and division-by-zero cases, and the clock answers. Press Run to see the output.
// JavaScript has no modulo operator. % is a truncated remainder: it is
// whatever is left after integer division that rounds TOWARDS ZERO.
const remainder = (a, n) => a % n;
// A real modulo is never negative for positive n. Two % calls get there.
const mod = (a, n) => ((a % n) + n) % n;
// Twelve-hour clock. Hour 0 is really hour 12.
const hoursBefore = (hour, back) => mod(hour - back, 12) || 12;
console.log('7 % 3, -7 % 3 :', 7 % 3, -7 % 3);
console.log('7 % -3, -7 % -3 :', 7 % -3, -7 % -3);
console.log('-6 % 3 :', -6 % 3, 'is it minus zero?', Object.is(-6 % 3, -0));
console.log('5.5 % 2 :', 5.5 % 2, '<- % is not integers-only');
console.log('7 % 0 :', 7 % 0);
console.log('Infinity % 3 :', Infinity % 3, 'and 3 % Infinity:', 3 % Infinity);
console.log('mod(-7, 3) :', mod(-7, 3), 'against -7 % 3 =', -7 % 3);
console.log('mod(-1, 12) :', mod(-1, 12), '<- one hour before midnight');
console.log('three before one:', hoursBefore(1, 3));
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.
test('7 % 3 is 1 and -7 % 3 is -1, so the sign follows the dividend', [7 % 3, -7 % 3], [1, -1]);
test('flipping the divisor sign changes nothing about the answer sign', [7 % -3, -7 % -3], [1, -1]);
test('an exact negative multiple leaves minus zero, which prints as 0', Object.is(-6 % 3, -0), true);
test('% is defined on non-integers too, so 5.5 % 2 is 1.5', 5.5 % 2, 1.5);
test('a zero divisor gives NaN rather than throwing', Number.isNaN(7 % 0), true);
test('Infinity % 3 is NaN, while 3 % Infinity is simply 3', [Number.isNaN(Infinity % 3), 3 % Infinity], [true, 3]);
test('the two-step mod lands inside the range for negatives', [mod(-7, 3), mod(-1, 12), mod(-13, 5)], [2, 11, 2]);
test('and it clears the minus zero on the way through', Object.is(mod(-6, 3), 0), true);
test('so three hours before one is ten, and the clock wraps past 12', [hoursBefore(1, 3), hoursBefore(3, 3), hoursBefore(12, 25)], [10, 12, 11]);
% is a remainder, and the sign it carries is the sign of the left operand. -7 % 3 is -1, not 2. That is correct arithmetic — -7 = 3 * (-2) + (-1) — but it is not what anyone wanting a wrap-around index means. Indexing an array with i % length works fine until i goes negative, and then it returns undefined silently.
((a % n) + n) % n is the fix. The second % is not redundant: it handles the case where the first remainder was already non-negative, so the result stays in range instead of becoming n too large. It also quietly repairs -0, because (-0 + 3) % 3 is 0.
Two edges worth knowing. 7 % 0 is NaN, which means a divide-by-zero in modular code does not throw; it poisons every later arithmetic step instead. And -6 % 3 is -0, which passes === 0, prints as 0, and stringifies as 0, so only Object.is can see it.
Common mistakes
- Using
%for wrap-around indexes. It works for positive numbers only. When the index can go negative, use((a % n) + n) % n. - Dropping the second
%.(a % n) + nalone pushes positive inputs out of range, somod(7, 3)would be 4. - Forgetting that
x % 0isNaN. It does not throw, so check for a zero divisor yourself before it spreads through your sums.
Try it yourself
- Write
prevIndex(i, length)that steps backward through an array and wraps from 0 to the last item. Test it on a list of 5. - What day of the week is 10 days before a Wednesday? Number the days 0 to 6 and use
mod. - Work out
mod(7, -3)by hand, then check it. What range doesmodland in whennis negative?