javascript

Modulus Operator (%)

Learn the JavaScript modulus operator (%). Discover how to find remainders, check for even/odd numbers, and use it in practical coding examples for beginners.

11 min read 8 sections Tutorial
Share

The modulus operator, written as a percent sign (`%`), is a special tool in JavaScript. It helps you find the "remainder" after a division. You will learn exactly what the modulus operator does, why it is useful, and how to use it in your code to solve common programming tasks.

Modulus Operator (%)

Modulus Operator (%)

The modulus operator, written as a percent sign (%), is a special tool in JavaScript. It helps you find the "remainder" after a division. You will learn exactly what the modulus operator does, why it is useful, and how to use it in your code to solve common programming tasks.

What is Modulus?

The modulus operator (%) calculates the remainder when one number is divided by another number.

Find Remainders

The primary use of modulus is to get the leftover value after one number is divided by another.

Check Even/Odd

It's perfect for easily determining if a number is even or odd by checking its remainder when divided by two.

Cyclic Operations

Modulus helps numbers wrap around, like making a counter go from 0 to 5, then back to 0 again.

Time Calculations

You can use it to convert large units of time into smaller, more readable units, like minutes into hours and minutes.

What is the Modulus Operator?

Getting Started

What is the Modulus Operator?

Imagine you have a group of items and you want to put them into smaller, equal groups. After you make all the equal groups, there might be some items left over. The modulus operator tells you exactly how many items are left over. It does not tell you how many full groups you made, only the remainder.

javascript
1// We have 10 cookies
2let totalCookies = 10;
3// We want to put them into bags that hold 3 cookies each
4let cookiesPerBag = 3;
5
6// The modulus operator (%) finds the remainder
7let cookiesLeftOver = totalCookies % cookiesPerBag;
8
9// What will 'cookiesLeftOver' be?
10// 10 divided by 3 is 3 with a remainder of 1.
11// So, 3 full bags are made, and 1 cookie is left over.
12console.log(cookiesLeftOver); // Output: 1

Not Regular Division!

Many beginners confuse the modulus operator (%) with the division operator (/). Remember, / gives you the quotient (how many times one number fits into another), while % gives you the remainder (what's left over).

How Modulus Works with Positive and Negative Numbers

How Modulus Works with Positive and Negative Numbers

The modulus operator works a bit differently when you use negative numbers. The most important rule to remember is that the sign of the result (the remainder) will always be the same as the sign of the first number. This first number is called the dividend. The second number is called the divisor.

javascript
1// Positive dividend, positive divisor
2let result1 = 10 % 3; // 10 divided by 3 is 3 with remainder 1
3console.log(result1); // Output: 1 (positive, matches 10)
4
5// Negative dividend, positive divisor
6let result2 = -10 % 3; // -10 divided by 3 is -3 with remainder -1
7console.log(result2); // Output: -1 (negative, matches -10)
8
9// Positive dividend, negative divisor
10let result3 = 10 % -3; // 10 divided by -3 is -3 with remainder 1
11console.log(result3); // Output: 1 (positive, matches 10)
12
13// Negative dividend, negative divisor
14let result4 = -10 % -3; // -10 divided by -3 is 3 with remainder -1
15console.log(result4); // Output: -1 (negative, matches -10)
✗ BadIncorrect Expectation
// Many people expect modulus to always return a positive result.
let value = -7 % 3;
// They might think the result should be 2, because 7 divided by 3 is 2 with a remainder of 1.
// Then they might try to make it positive. This is wrong in JavaScript.
✓ GoodCorrect Behavior
// In JavaScript, the sign of the modulus result always matches the dividend.
let value = -7 % 3;
// -7 divided by 3 is -2 with a remainder of -1.
// The dividend (-7) is negative, so the result is also negative.
console.log(value); // Output: -1

Common Uses of the Modulus Operator

Common Uses of the Modulus Operator

The modulus operator is very versatile. It is not just for finding remainders in math class. Programmers use it every day for practical tasks. Let's look at two very common ways you will use modulus in your own code.

Checking for Even or Odd Numbers
// A number is even if it has no remainder when divided by 2.
// A number is odd if it has a remainder of 1 (or -1) when divided by 2.
let num1 = 10;
let num2 = 7;
// Check if num1 is even
if (num1 % 2 === 0) {
console.log(num1 + " is even."); // 10 is even.
}
// Check if num2 is odd
if (num2 % 2 !== 0) {
console.log(num2 + " is odd."); // 7 is odd.
}
VS
Keeping Numbers within a Range (Wrapping Around)
// Modulus can make numbers "wrap around" like a clock face.
// This is useful for things like array indexes or carousels.
let maxCount = 5; // Numbers should go 0, 1, 2, 3, 4, then back to 0
let currentNumber = 7;
// To wrap 7 around a range of 0 to 4 (5 total items):
// 7 % 5 = 2. So, it effectively becomes 2.
let wrappedNumber = currentNumber % maxCount;
console.log(wrappedNumber); // Output: 2
// If currentNumber was 4, then 4 % 5 = 4.
// If currentNumber was 5, then 5 % 5 = 0.
// This ensures the number is always between 0 and (maxCount - 1).

When to Use Each Approach

Use the even/odd check when you need to categorize numbers based on divisibility by two. Use the wrapping approach when you need to cycle through a fixed set of items, like images in a slideshow or days of the week.

Practical Examples: Building with Modulus

Practical Examples: Building with Modulus

Let's see how the modulus operator can be used in a real-world coding scenario. We will create a simple example where we want to highlight every third item in a list. This is a common task in web development for styling rows or items.

1

Create a List of Items

First, imagine you have a list of data, like names of students. We will use an array to hold these names. An array is a list of items.

javascript
1let students = [
2 "Alice", "Bob", "Charlie", "David", "Eve",
3 "Frank", "Grace", "Heidi", "Ivan", "Judy"
4];
5console.log("Total students: " + students.length);
2

Loop Through the Items

We need to go through each student in our list one by one. A for loop is perfect for this. The loop will give us an index for each student, starting from 0.

javascript
1for (let i = 0; i < students.length; i++) {
2 // 'i' will be 0, then 1, then 2, and so on.
3 console.log(`Student at index ${i}: ${students[i]}`);
4}
3

Use Modulus to Find Every Third Item

Now, we use the modulus operator. We want to find every third item. So, we will check if the index i divided by 3 has a remainder of 0. Remember, i starts at 0, so the 0th, 3rd, 6th, etc., items will be highlighted.

javascript
1for (let i = 0; i < students.length; i++) {
2 // If the remainder of 'i' divided by 3 is 0, it's every third item (0-indexed).
3 if (i % 3 === 0) {
4 console.log(`HIGHLIGHT: Student at index ${i}: ${students[i]}`);
5 } else {
6 console.log(`Student at index ${i}: ${students[i]}`);
7 }
8}
4

Adjusting for 1-based Counting

Sometimes you want to highlight the 1st, 4th, 7th item (1-based counting). You can adjust by checking (i + 1) % 3 === 0 or i % 3 === 2 (for the 3rd item, which has index 2).

javascript
1for (let i = 0; i < students.length; i++) {
2 // (i + 1) makes the count start from 1 instead of 0.
3 if ((i + 1) % 3 === 0) {
4 console.log(`HIGHLIGHT (1-based): Student ${i + 1}: ${students[i]}`);
5 } else {
6 console.log(`Student ${i + 1}: ${students[i]}`);
7 }
8}

Ignoring Modulus for Cyclic Logic

If you try to manage cyclic logic (like moving to the next item in a list and wrapping around) without modulus, your code can become very complicated. You might end up with if statements checking if an index is too high, leading to bugs like 'index out of bounds' errors or infinite loops if not handled perfectly.

Modulus Operator Reference

Modulus Operator Reference

OperationExampleResultMeaning
Positive Modulus`10 % 3`110 divided by 3 is 3 with 1 left over.
Negative Dividend`-10 % 3`-1The result's sign matches the dividend (-10).
Modulus by 1`anyNum % 1`0Any whole number divided by 1 has no remainder.
Smaller Dividend`3 % 10`3If the dividend is smaller than the divisor, the dividend itself is the remainder.

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

What is the result of 20 % 6?

Quick Check

Which code snippet correctly checks if a variable x is an odd number?

Quick Check

What is the output of console.log(-13 % 5);?

Quick Check

You have an array of 5 items. If you want to cycle through its indexes (0 to 4) using a variable i that keeps increasing, which expression correctly gets the current index, wrapping around when i goes beyond 4?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1Purpose — The modulus operator (%) finds the remainder of a division operation.
  • 2Syntax — It is used between two numbers: dividend % divisor.
  • 3Result Sign — The sign of the modulus result always matches the sign of the dividend (the first number).
  • 4Even/Odd Check — A number is even if number % 2 === 0; it's odd if number % 2 !== 0.
  • 5Wrapping Around — Use index % length to keep a number within the bounds of an array or list, causing it to cycle.
  • 6Division by Zero — Using 0 as the divisor (number % 0) will result in NaN (Not a Number).
  • 7Decimal Numbers — Modulus can work with decimals, but be mindful of floating-point inaccuracies.
  • 8Common Mistake — Do not confuse % (modulus/remainder) with / (division/quotient).
  • 9Applications — Useful for styling alternating rows, game logic, time conversions, and data validation.
  • 10Efficiency — It's a very efficient way to perform remainder calculations in JavaScript.

Arithmetic Operators

Explore other basic math operations like addition, subtraction, multiplication, and division in JavaScript.

Conditional Statements

Learn how to use if, else if, and else to make decisions in your code based on conditions.

Loops

Understand for and while loops to repeat code blocks multiple times, often used with modulus.

Arrays

Discover how to store collections of data in ordered lists and access elements using indexes.

Congratulations!

You have now learned all about the modulus operator (%) in JavaScript! You can use it to find remainders, check for even or odd numbers, and create wrapping effects in your code. Keep practicing to become a master programmer!

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning