JavaScript Remainder (%) Operator

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);  // 0

Remainder operator syntax Top ↑

dividend % divisor

Although this operator is often called “modulus” in everyday programming, JavaScript's % follows remainder semantics: the sign of a non-zero result follows the dividend.

Check whether a number is even or odd Top ↑

const value = 27;
if (value % 2 === 0) {
  console.log("Even");
} else {
  console.log("Odd");
}

Negative numbers: remainder is not always mathematical modulo Top ↑

console.log(-13 % 5); // -3
console.log(13 % -5); // 3

If 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)); // 4

Reset a repeating counter Top ↑

let counter = 0;
const cycleLength = 30;

counter = (counter + 1) % cycleLength;
console.log(counter);

See the timer tutorial and resetting-counter demo.

Change every alternate array item Top ↑

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.

Wrap an array index Top ↑

const items = ["A", "B", "C"];
let index = 2;
index = (index + 1) % items.length;
console.log(items[index]); // A

Remainder with a zero divisor Top ↑

console.log(10 % 0); // NaN

Remainder with decimal values Top ↑

The % 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 effects

Remainder with BigInt Top ↑

The 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); // 2n

Common remainder mistakes Top ↑

The 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.

Remainder operator demos Top ↑

Try the alternate-item demo and counter-reset demo.

Math.abs()




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer