Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Remainder (%)

The remainder of a division.

Available since: ES1

Syntax

a % b

Examples

The remainder and an even check:

console.log(10 % 3);
console.log(8 % 2 === 0);

Output:

1
true

Every third element and cycling around:

const colors = ['red', 'green', 'blue'];
 
for (let i = 0; i < 5; i++) {
  console.log(i, colors[i % colors.length]);
}

Output:

0 red
1 green
2 blue
3 red
4 green

Notes

The result takes the sign of the dividend: -7 % 3 is -1. So check for odd numbers with n % 2 !== 0, not n % 2 === 1.

See also

  • Math.floor — Rounds a number down to an integer.
  • Math.trunc — Drops the fractional part of a number.

In the tutorial

  • Operators — JavaScript arithmetic operators, the remainder, operator precedence, compound assignment, ++ and --.

Thanks for reading!

Donate to the site — we work hard for you.