Remainder (%)
The remainder of a division.
Available since: ES1
Syntax
a % bExamples
The remainder and an even check:
console.log(10 % 3);
console.log(8 % 2 === 0);Output:
1
trueEvery third element and cycling around:
const colors = ['red', 'green', 'blue'];
for (let i = 0; i < 5; i++) {
console.log(i, colors[i % colors.length]);
}Output:
0 red
1 green
2 blue
3 red
4 greenNotes
The result takes the sign of the dividend: -7 % 3 is -1. So check for odd numbers with n % 2 !== 0, not n % 2 === 1.
See also
- Math.floor — Rounds a number down to an integer.
- Math.trunc — Drops the fractional part of a number.
In the tutorial
- Operators — JavaScript arithmetic operators, the remainder, operator precedence, compound assignment, ++ and --.