Documentation

Student-friendly HTML, CSS, and JavaScript reference with examples

Sections

Modulus

5 % 3 // 2

Math is simple, but the modulus operator takes a bit of getting used to. % divides and
gives you the remainder instead of the result.

5 % 3   // 2 — 3 goes into 5 once, with 2 left over
8 % 4   // 0 — divides evenly, nothing left over

Common usecase: is the number even or odd?

If you need to know whether a number is even or odd, you need % 2. It will always
return either 1 or 0 — in fact, if you count from 1 to 100, the result of % 2 is
always one of those two.

1 % 2    // 1
2 % 2    // 0
3 % 2    // 1
4 % 2    // 0
5 % 2    // 1
6 % 2    // 0
7 % 2    // 1
8 % 2    // 0
9 % 2    // 1
10 % 2   // 0

0 means even, 1 means odd.