The JavaScript remainder operator % returns the remainder left after dividing one number by another. It is commonly used for even/odd checks, repeating patterns, cycling counters, and grouping values.
console.log(123 % 5); // 3
console.log(12 % 2); // 0dividend % divisorAlthough this operator is often called “modulus” in everyday programming, JavaScript's % follows remainder semantics: the sign of a non-zero result follows the dividend.
const value = 27;
if (value % 2 === 0) {
console.log("Even");
} else {
console.log("Odd");
}console.log(-13 % 5); // -3
console.log(13 % -5); // 3If you need a non-negative wrap-around result for a positive modulus n, normalize it:
function mod(value, n) {
return ((value % n) + n) % n;
}
console.log(mod(-1, 5)); // 4let counter = 0;
const cycleLength = 30;
counter = (counter + 1) % cycleLength;
console.log(counter);See the timer tutorial and resetting-counter demo.
const scripts = ["PHP", "ASP", "JavaScript", "HTML"];
scripts.forEach((name, index) => {
const group = index % 2 === 0 ? "even index" : "odd index";
console.log(name, group);
});See displaying array elements, the HTML span tutorial, and the alternate-row demo.
const items = ["A", "B", "C"];
let index = 2;
index = (index + 1) % items.length;
console.log(items[index]); // Aconsole.log(10 % 0); // NaNThe % operator also works with finite decimal Number values. Because JavaScript uses binary floating-point numbers, decimal remainders can show representation effects.
console.log(5.5 % 2); // 1.5
console.log(0.3 % 0.1); // may expose floating-point precision effectsThe operator also works with BigInt when both operands are BigInts. Do not mix a Number and a BigInt in the same arithmetic operation.
console.log(17n % 5n); // 2nThe main mistake is assuming % always returns a non-negative mathematical modulo. With a negative dividend, JavaScript can return a negative remainder. Normalize it when you need cyclic indexes that must stay in the range 0 through n - 1.
Try the alternate-item demo and counter-reset demo.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.