The Remainder Operator (%)
You'll learn how to find what's left over after division using the % operator.
What Is the Remainder Operator?
The remainder operator (%) returns what's left over when one number is divided by another. If you divide 10 by 3, you get 3 with 1 left over—that leftover is the remainder.
Think of it like sharing cookies: if you have 10 cookies and 3 friends, each friend gets 3 cookies (3 × 3 = 9), and you have 1 cookie remaining.
Basic Syntax
let remainder = 10 % 3; // 1
The expression 10 % 3 asks: "What's left after dividing 10 by 3?"
Common Examples
7 % 2; // 1 (7 divided by 2 is 3 remainder 1)
10 % 5; // 0 (10 divided by 5 is exactly 2, no remainder)
15 % 4; // 3 (15 divided by 4 is 3 remainder 3)
5 % 10; // 5 (5 divided by 10 is 0 remainder 5)
Not the Same as Mathematical Modulus
In mathematics, "modulus" always returns positive values. JavaScript's % operator preserves the sign of the first operand:
-10 % 3; // -1 (not 2)
10 % -3; // 1
Common Patterns
Even or odd detection:
5 % 2; // 1 (odd numbers have remainder 1)
6 % 2; // 0 (even numbers have remainder 0)
Cycling through values:
0 % 3; // 0
1 % 3; // 1
2 % 3; // 2
3 % 3; // 0 (cycles back)
4 % 3; // 1
Key Takeaway: The remainder operator % returns what's left over after division, which is useful for detecting patterns like even/odd numbers or cycling through ranges.