Remainder Operator (%) in JavaScript

🔍 What is the Remainder Operator?

The % operator in JavaScript is known as the remainder operator (sometimes informally called the modulus operator). It returns the remainder left over when one number is divided by another.

>>“When division doesn't go perfectly, the remainder tells the rest of the story.” 📘

📌 Syntax

Remainder Operator Syntax

result = dividend % divisor;

🧠 How It Works

The remainder operator calculates:

a % b → what’s left after dividing a by b

It's different from / which gives you the quotient. For example:

Basic Example

console.log(10 / 3);  // 3.333...
console.log(10 % 3);  // 1 (because 3 * 3 = 9, remainder = 1)

📊 Examples

Various Remainder Examples

console.log(7 % 2);   // 1 (7 divided by 2 is 3 with remainder 1)
console.log(10 % 5);  // 0 (10 is exactly divisible by 5)
console.log(15 % 4);  // 3 (4 * 3 = 12, remainder is 3)
console.log(4 % 10);  // 4 (divisor is bigger than dividend)
console.log(-7 % 3);  // -1 (sign follows the dividend)

Note

⚠️ The sign of the result always follows the dividend (the number on the left).

🎯 Common Use Cases

  • 💡 Checking Even or Odd: if (num % 2 === 0) means it's even.
  • 🔁 Loop Wrapping: Cycling through values in arrays or counters.
  • Timed Intervals: Run a function every N iterations.

Even/Odd Checker

const num = 7;
if (num % 2 === 0) {
  console.log("Even");
} else {
  console.log("Odd"); // Output: "Odd"
}

🧪 Difference from Math.floor & Math.trunc

While % gives the remainder, methods like Math.floor() give you the largest whole number less than or equal to the division result.

Math.floor vs %

console.log(Math.floor(7 / 3));  // 2
console.log(7 % 3);  // 1

📚 Learn More

>>“Sometimes, what’s left is more important than what’s gone.” – Think like a dev. 🔍