What is the purpose of module (%) operator in javascript?

For the operation n % d, n is called the dividend and d is called the divisor. The operation returns NaN if one of the operands is NaN, n is ±Infinity, or if d is ±0. Otherwise, if d is ±Infinity or if n is ±0, the dividend n is returned.

When both operands are non-zero and finite, the remainder r is calculated as r := n - d * q where q is the integer such that r has the same sign as the dividend n while being as close to 0 as possible.

Note that while in most languages, '%' is a remainder operator, in some (e.g. Python, Perl) it is a modulo operator. Modulo is defined as k := n - d * q where q is the integer such that k has the same sign as the divisor d while being as close to 0 as possible. For two values of the same sign, the two are equivalent, but when the operands are of different signs, the modulo result always has the same sign as the divisor, while the remainder has the same sign as the dividend, which can make them differ by one unit of d. To obtain a modulo in JavaScript, in place of n % d, use ((n % d) + d) % d. In JavaScript, the modulo operation (which doesn't have a dedicated operator) is used to normalize the second operand of bitwise shift operators (<<, >>, etc.), making the offset always a positive value.


The JavaScript modulo operator returns the remainder of a division sum. To calculate the remainder of a division sum, use the percentage sign (%). The syntax for the modulo operator is: (number_one % number_two).

How to Use the JavaScript Modulo Operator

Have you ever seen a percentage sign accompanied by a few numbers in JavaScript? You’ve maybe thought that it is something to do with calculating percentages. That’s not the case. In JavaScript, the percentage sign is used to calculate remainders.

The percentage sign (%) is the modulo operator. It divides two numbers and calculates the remainder left over, if any. It’s commonly used to find out if a number is odd or even.

What is the purpose of module (%) operator in javascript?

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest
First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy , and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

In this guide, we’re going to discuss how to use the JavaScript modulo operator. We’ll walk through an example of this operator in action to help you get started.

What is the JavaScript Modulo Operator?

The JavaScript modulo operator, represented by a percentage sign, returns the remainder of a division sum. You can refer to the modulo operator by this name, as a modulus operator, or as a remainder operator.

Not all numbers can be evenly divided. 9 cannot be divided by 4 without yielding a decimal number. If you’re looking for precision, a decimal number is fine. There are some cases where you’ll want to know how many numbers are left over from a calculation.

The modulo operator tells you what is left over when a number has been divided as many times as it can be. The remainder of 9 divided by 4 is 1. 4 goes into 9 twice. There is 1 left over.

The syntax for the modulo operator is:

Our code returns:

You can use the modulo operator in JavaScript with negative values:

Our code returns:

Modulo Operator JavaScript Example

We want to create a tool that tells a young person how much will be left over if they spend money on video games. We’ll start building our program by declaring two JavaScript variables :

var game_cost = 40;
var balance = 122;

The first variable stores the cost of a game. Our second variable stores how much money we have in our bank account. Let’s use the modulo operator to find out how much we would have left over if we spent all our money on games:

console.log(balance % game_cost);

Our code returns: 2. This tells us that if we spend all of our money on video games, we will have $2 left over.

What is the purpose of module (%) operator in javascript?

"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"

Venus, Software Engineer at Rockbot

Using the Division Operator

The modulo operator tells you how much is left over by dividing two numbers. This does not tell us how many games we can buy. We can use the JavaScript division operator to calculate how many games we can buy.

console.log(Math.round((balance / game_cost), 0));

In this code, we use the division operator (/) to calculate how many games we can buy. We have then rounded this value to the nearest whole value. This is because you cannot buy a portion of a game; you have to buy a whole game.

Our code returns: 3.

These two operations combined tell us that we can afford three video games. We will have $2 left over after we have bought these games.

JavaScript Check if a Number is Odd or Even

The modulo operator is used to check if a number is odd or even. This is because even numbers have no remainders when divided by two. Odd numbers, on the other hand, have a remainder if they are divided by two.

We’re going to build an application that tells us whether we can purchase an even or odd number of candy bars. This program assumes we have a certain amount of money. Let’s start by declaring variables which track the cost of a candy bar and how much money we have:

var cost = 1.50;
var balance = 3.50;

We’ll then use the division operator to find out how many we can buy:

var can_buy = Math.round((balance / cost), 0);
console.log(can_buy);

This code returns: 2. This tells us we can afford to purchase two full candy bars. The JavaScript Math.round() method rounds the value returned by our division sum to the nearest decimal place. This is useful because we cannot buy part of a candy bar.

Next, we can use the modulo operator to check if the number of candy bars we can buy is odd or even:

if (can_buy % 2 != 0) {
	console.log("You can buy an even number of candy bars.");
} else {
	console.log("You can buy an odd number of candy bars.");
}

Our code uses the modulo operator to check if there is any remainder left over after dividing the number by two. If there is, the number is odd; otherwise, the number is even.

Our code uses the modulo operator to check if there is any remainder left over after dividing the number by two. We use a JavaScript if statement to specify what should happen if there is a remainder. If there is, the number is odd; otherwise, the number is even.

Our code returns:

You can buy an even number of candy bars.

The value of “can_buy” is 2. This is an even number so the code inside our if statement runs.

Conclusion

The JavaScript modulo operator calculates the remainder left over after dividing two numbers. It is commonly used with an if statement to evaluate whether a number is odd or even. The modulo operator is represented by a percentage sign.

Do you want to learn more about how to code in JavaScript? Read our How to Learn JavaScript guide . You’ll find top tips on how to learn JavaScript and a list of learning resources you can leverage.

Our code returns: You can buy an even number of candy bars. The value of “can_buy” is 2. This is an even number so the code inside our if statement runs.

Conclusion

The modulo operator calculates the remainder left over after dividing two numbers. It is commonly used with an if statement to evaluate whether a number is odd or even.

Now you’re ready to start using the JavaScript modulo operator like an expert!

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.

What's Next?

  • What is the purpose of module (%) operator in javascript?

    Want to take action?

    Get matched with top bootcamps

James Gallagher

About the author: James Gallagher is a self-taught programmer and the technical content manager at Career Karma. He has experience in range of programming languages and extensive expertise in Python, HTML, CSS, and JavaScript. James has written hundreds of programming tutorials, and he frequently contributes to publications like Codecademy, Treehouse, Repl.it, Afrotech, and others.

    What is the purpose of using modulus operator?

    The modulus operator is added in the arithmetic operators in C, and it works between two available operands. It divides the given numerator by the denominator to find a result. In simpler words, it produces a remainder for the integer division. Thus, the remainder is also always an integer number only.

    What is the percentage operator in JavaScript?

    The % operator is one of the "Arithmetic Operators" in JavaScript, like / , * , + , and - . The % operator returns the remainder of two numbers. It is useful for detecting even/odd numbers (like to make stripes) and for restricting a value to a range (like to wrapping an animated ball around) .

    What is modulus operator in JavaScript with example?

    Modulus is a related concept, but handles negative numbers differently. For example, -21 % 5 === -1 , because the remainder always takes the sign of the left number. However, a true modulus operator would always return a positive value, so 21 modulo 5 would equal 4.

    What are the modulus in node JS?

    Your Modulus application runs on one or more mini-servers which they call Servos. You can add or remove Servos from your application as needed as your load and your needs change; Modulus will automatically load balance traffic across your Servos, with built-in session affinity to make things run even more efficiently.