The modulo operator in JavaScript is represented by the % symbol and returns the remainder after dividing one number by another. It is commonly used for tasks like checking if a number is even or odd, wrapping values within a specific range (e.g., 0 to 360 for angles), and managing cyclic behavior in applications such as animations or game development.
Key Behavior
The result always takes the sign of the dividend (the first operand).
For example:
13 % 5→3-13 % 5→-313 % -5→3-13 % -5→-3
Common Use Cases
Even/Odd Check:
Usen % 2 === 0to test if a number is even.Wrapping Values:
To keep a value within a range (e.g., 0 to 3), usevalue % range.const angle = 400; const normalized = angle % 360; // Returns 40Cyclic Logic:
Useful in loops, like triggering an event every 5th iteration:let counter = 0; setInterval(() => { counter++; if (counter % 5 === 0) { console.log("Trigger every 5 seconds"); } }, 1000);
Important Note
JavaScript’s % is a remainder operator, not a true modulo operator (like in Python). When dealing with negative numbers, the result follows the dividend’s sign. To emulate true modulo (same sign as divisor), use:
const modulo = (n, m) => ((n % m) + m) % m;This operator is well-supported across all modern browsers and is essential for mathematical and logical operations in JavaScript.
It's the remainder operator and is used to get the remainder after integer division. Lots of languages have it. For example:
10 % 3 // = 1 ; because 3 * 3 gets you 9, and 10 - 9 is 1.
Apparently it is not the same as the modulo operator entirely.
Answer from MarioDS on Stack Overflow