Basics
Remainder %
The remainder left after dividing one number by another.
Why it exists
The remainder answers questions that come up all the time: does a number divide evenly, which "lap" are we on and where inside it. Even or odd, every third item, a clock passing midnight, an endless image carousel — all of that is %. Without it you'd write subtraction in a loop or tricky formulas with rounding.
Where it's used
- Even or odd:
n % 2 === 0— striped table rows, alternating turns. - "Every Nth":
i % 3 === 0— products in rows of 3, an ad after every 5th post. - Wrapping around:
(index + 1) % slides.length— after the last slide comes the first again. - Time:
minutes % 60— minutes within the hour,hours % 24— the hour within the day.
Syntax
a % bExamples
10 % 3; // → 1
9 % 3; // → 0 — 9 divides by 3
-7 % 3; // → -1const slides = 4;
let current = 3;
current = (current + 1) % slides;
current; // → 0 — after the last comes the firstconst totalMinutes = 135;
Math.floor(totalMinutes / 60); // → 2
totalMinutes % 60; // → 15 — so 2 h 15 min-3 % 2; // → -1
-3 % 2 === 1; // → false
-3 % 2 !== 0; // → trueResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
a % b is what's left of a after subtracting b as many whole times as it fits. 17 % 5: five fits 3 times (15), and 2 is left.
In JavaScript the remainder takes the sign of the dividend (the left number): -7 % 3 is -1, not 2 as in some maths textbooks. That's why the reliable even check compares with zero, n % 2 === 0, and the odd check is n % 2 !== 0.
Fractions work too: 5.5 % 2 is 1.5.
Traps
How it differs from…
- Arithmetic operators
/gives the quotient (17 / 5is3.4),%gives the remainder (17 % 5is2). Together with Math.floor they split a number into "how many whole times" and "how much is left".
When to pick something else
If you need the "mathematical" remainder that's never negative (say, an index when stepping back in a carousel), write ((a % n) + n) % n — plain % gives a negative result for negative numbers.