References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript Remainder % operator

Operator JavaScript All modern browsers Updated
Quick answer

The remainder operator % returns what's left over after dividing one number by another. 10 % 3 is 1. Often called "modulo," it's used to test even/odd (n % 2 === 0), to wrap a value into a range, and to cycle through items. Note it keeps the sign of the left operand for negatives.

Overview

% gives the remainder of a division. 10 % 3 is 1 because 3 goes into 10 three times with 1 left over. It's commonly called the modulo operator, and despite being simple it powers a surprising number of patterns.

The classic uses: even or odd is n % 2 (0 for even, 1 for odd); every Nth item is i % n === 0; and wrapping a value into a range is (i % length), which is how you cycle an index back to the start of an array — perfect for carousels, round-robins and clock arithmetic ((hour + 5) % 12).

One thing to know for negatives: JavaScript's % keeps the sign of the left operand, so -7 % 3 is -1, not 2. That differs from a true mathematical modulo. When you need an always-positive result (common when wrapping with a possibly-negative index), use ((n % m) + m) % m. It works on decimals too, though floating-point rounding applies.

Syntax

a % b

10 % 3      // 1
8 % 2       // 0  (even)
7 % 2       // 1  (odd)
-7 % 3      // -1 (sign follows the left operand)
((n % m) + m) % m  // always-positive remainder

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  const colors = ['red', 'green', 'blue'];
  const lines = [];

  // cycle through colors with wrapping
  for (let i = 0; i < 7; i++) {
    lines.push(i + ' -> ' + colors[i % colors.length]);
  }

  document.getElementById('out').textContent = lines.join('\n');
</script>

Best practices

  • Test even/odd with n % 2 === 0.
  • Wrap an index into an array with i % arr.length to cycle back to the start.
  • For an always-positive result with negatives, use ((n % m) + m) % m.
  • Remember % is remainder (sign follows the dividend), not a strict mathematical modulo.

Frequently asked questions

What does the % operator do in JavaScript?
It returns the remainder after dividing the left number by the right, e.g. 10 % 3 is 1.
How do I check if a number is even or odd?
Use n % 2: it's 0 for even numbers and 1 for odd ones, so n % 2 === 0 tests for even.
Why is -7 % 3 negative?
JavaScript's % takes the sign of the left operand. For an always-positive result use ((n % m) + m) % m.
How do I cycle an index through an array?
Use index % arr.length so the index wraps back to 0 when it reaches the end.