# JavaScript % Operator: An Ultimate Guide to Modulos

In mathematics, the modulo gives you the remainder of the division.

To calculate the remainder in the division in JavaScript, use the modulo operator (%).

For example:

```const r = 10 % 3
console.log(r)```

Output:

`1`

You can interpret this as sharing 10 slices of pizza with 3 eaters. As a result of a fair share, there will be one leftover slice. This is the result of the modulo.

In JavaScript, the modulo has many practical use cases. The most common use cases include checking if a number is odd/even, or checking if a number is a prime number.

This guide teaches you all you need to know about the modulo operator in JavaScript.

Before jumping into calculating modulo in JavaScript, let’s take a look at modulos in maths.

## Modulo in Mathematics

In mathematics, modulo describes the remainder in the division. In math, the modulo is commonly denoted with mod.

`a mod b`

Where:

• a is called the dividend.
• b is called the divisor.

The modulo returns the remainder in the division.

For example:

`7 mod 3 = 1`

To see why it works this way, think about sharing 7 apples with 3 persons fairly. In other words, each person should get the same number of apples.

To make this possible, you should share 2 apples with each person. This means you have shared 6 apples. Thus, there is one leftover apple. This is the remainder in the division.

Another example of modulos is a 12-hour clock. When you count the time, you count up to 12 and go back to 0.

For example, let’s figure out what time is it exactly 11 hours after 7:00.

To do this, you cannot add 11 to 7:00, because that would give 18:00. Instead, add 11 hours to 7:00 until you reach 12:00. Then the 6 leftover hours are added to the new round to make it to 6:00.

This is exactly how modulo works. In other words, an easier solution to the above example is by calculating 11 + 7 mod 12 which results in 6.

`18 mod 12 = 6`

So in a 12-hour clock, 18:00 and 6:00 are the same thing.

Mathematically this fact is denoted by:

`18 ≡ 6 (mod 12)`

This reads “18 and 6 are congruent to modulo 12”.

Generally, in modular arithmetic, you can express these modular relationships by:

`a ≡ b (mod n)`

Which means “a and b are congruent to modulo n”.

That’s enough for the theory.

Now you understand what is modular arithmetic. Next, let’s move on to calculating modulos in JavaScript.

## Modulo in JavaScript

In JavaScript, you can use the % operator to calculate modulo.

`a % b`

You can compute modulo with numeric types int and float and negative numbers.

### Modulo with Integers in JavaScript

Usually, you calculate the modulo between two integers.

Here are some examples:

```console.log(4 % 3)      // 1
console.log(10 % 7)     // 3
console.log(78 % 14)    // 8
console.log(1000 % 10)  // 0```

As you can see, the result of the modulo can also be 0. But taking a modulo with 0 is meaningless. The result is always NaN.

`console.log(1000 % 0)  // NaN`

Now you have the understanding of how to calculate remainders in JavaScript using integers.

Next, let’s see some examples of using negative numbers and modulo.

### Modulo with Negative Numbers

Calculating modulos of negative numbers is possible in JavaScript.

But notice that different programming languages calculate negative modulos differently. The reason is that it’s unclear whether the result should have the sign of the dividend or the divisor.

In JavaScript, the result of modulo takes the sign of the dividend (the value on the left).

For example, the result of this calculation is positive, even though the divisor is negative:

`console.log(7 % -4)  // 3`

But in Python, the same calculation yields a different result that has the sign of the divisor:

```>>> 7 % -4
-1```

But why are the results not the same?

It boils down to how the modulo is calculated under the hood.

As it turns out, the modulo is calculated differently in JavaScript as opposed to Python.

Here is how a % b is calculated behind the scenes:

```javascript: r = a - (b * trunc(a / b))
python:     r = a - (b * floor(a / b))```

Take a look at the last term in both of these equations. There is a difference. In JavaScript, the last term is trunc(a / b). In Python, it is floor(a / b).

• trunc(a / b) means a truncated division. This rounds a negative number toward 0.
• floor(a / b) means floor division. This rounds a negative number away from 0.

Here is an illustration of both of these functions:

Both floor() and trunc() round positive values down to the nearest integer value. In other words, they work the same way with positive numbers.

This causes the differences with modulos using negative values.

Let’s use the above equation to manually calculate 7 % -4 in JavaScript and Python.

Here is the JavaScript version:

```r = a - (b * trunc(a / b))
a = 7
b = -4

r = 7 - (-4 * trunc(7 / -4))
= 7 - (-4 * trunc(-1.75))
= 7 - (-4 * -1)
= 7 - 4
= 3```

And here is Python’s version:

```r = a - (b * floor(a / b))
a = 7
b = -4

r = 7 - (-4 * floor(7 / -4))
= 7 - (-4 * floor(-1.75))
= 7 - (-4 * -2)
= 7 - 8
= -1```

As you can see, the JS version gives 3 but Python gives -1.

To recap, negative modulos might give different values in different languages. They are calculated in a different way due to the unclarity of how to handle the negative sign.

Next, let’s take a look at modulos between floating-point numbers.

### Modulo with Floats

Similar to how you can use integers to calculate modulos, you can use floats.

Here are some examples:

```console.log(10.5 % 4.5)    // 1.5
console.log(10 % 1.5)      // 1
console.log(12.5 % 3.5)    // 2
console.log(10.0 % 3.0)    // 1```

Similar to other arithmetic operations in JavaScript, you may encounter floating-point issues with modulos.

For example:

`console.log(10.0 % 3.1) // 0.6999999999999997`

Now you have taken a complete overview of how to calculate remainders in JavaScript.

Next, let’s discuss the operator precedence in calculations that involve other operators.

### Operator Precedence with Modulos

Operator precedence describes what operations take place first when combined in the same equation.

In JavaScript, the modulo operator has the same precedence level as:

• Multiplication (*)
• Division (/)
• Floor division (//).

For example, if you multiply first and then take a modulo, the multiplication takes place first.

But if you add two numbers and take a modulo, the modulo precedes.

For instance:

`console.log(3 * 4 % 5 - 6) // -4`

To better understand how JavaScript calculates this, place parenthesis around the terms.

`((3 * 4) % 5) - 6`

JavaScript evaluates this as follows:

• ((3 * 4) % 5) – 6
• (12 % 5) – 6
• 2 – 6
• -4

Now you have a good understanding of the modulo in general. Let’s take a look at some common applications next.

## Common Use Cases of Modulo in JavaScript

There are many use cases for modulo in JavaScript.

A common example is to check whether a number is odd or even. Another popular task is to check if a number is a prime number.

Let’s see these and a couple of more examples next.

### Use Modulo to Deal with Periodicity

Modulo helps you when there is periodicity in your code.

Think about a game character. It runs out of the screen on the right side and pops back in on the left side. The code that makes this possible defines the player’s x-position modulo screen width.

In layman’s terms, when the player’s x position exceeds the screen width, the modulo operation turns it back to 0.

`x_pos = x_pos % screen_width`

Let’s see another example using the 12-hour clock we talked about earlier.

Even though there are 24 hours in a day, a 12-hour clock wraps around itself 12 hours before the day is over.

But it is still a perfectly valid way to track time.

This is possible because for example 15:00 on a 24-hour clock is 3:00. The only problem is the time points same spot twice a day. But because we can clearly distinguish day from night, this is not an issue.

Let’s simulate a 12-hour clock in JavaScript.

To display the hours of the day in a 12-hour clock, take a modulo between the hour of the day and 12.

Here is how it looks in code:

```function wallclock(hour) {
const result = hour % 12
console.log(`\${hour}:00 is \${result}:00 on a 12-hour clock`)
}

// Creates an array from 0 to 24
const hours = [...Array(25).keys()]

for (hour of hours) {
wallclock(hour)
}```

Output:

```0:00 is 0:00 on a 12-hour clock
1:00 is 1:00 on a 12-hour clock
2:00 is 2:00 on a 12-hour clock
3:00 is 3:00 on a 12-hour clock
4:00 is 4:00 on a 12-hour clock
5:00 is 5:00 on a 12-hour clock
6:00 is 6:00 on a 12-hour clock
7:00 is 7:00 on a 12-hour clock
8:00 is 8:00 on a 12-hour clock
9:00 is 9:00 on a 12-hour clock
10:00 is 10:00 on a 12-hour clock
11:00 is 11:00 on a 12-hour clock
12:00 is 0:00 on a 12-hour clock
13:00 is 1:00 on a 12-hour clock
14:00 is 2:00 on a 12-hour clock
15:00 is 3:00 on a 12-hour clock
16:00 is 4:00 on a 12-hour clock
17:00 is 5:00 on a 12-hour clock
18:00 is 6:00 on a 12-hour clock
19:00 is 7:00 on a 12-hour clock
20:00 is 8:00 on a 12-hour clock
21:00 is 9:00 on a 12-hour clock
22:00 is 10:00 on a 12-hour clock
23:00 is 11:00 on a 12-hour clock
24:00 is 0:00 on a 12-hour clock ```

### Odd or Even?

To check if a number is odd or even, use the modulo.

• If the number is even, it is evenly divisible by 2. In other words, `number mod 2` yields 0.
• If the number is not even, it is odd.

For instance:

```function isEven(number) {
return number % 2 == 0
}

console.log(isEven(10))
console.log(isEven(7))```

Output:

```true
false```

Similarly, to find out if a number is odd, you can either use the isEven() function with negation:

```function isOdd(number) {
return !isEven(number)
}```

Or you can use the fact that any odd number modulo 2 gives a remainder of division of 1:

```function isOdd(number) {
return number % 2 == 1
}```

### Repeat Code in Intervals

Sometimes, when running a loop, you don’t want to run code at each iteration. Instead, you specify an interval on how often a code should be run.

To run code in intervals, check if the current iteration index is evenly divisible by the interval. In other words, use modulo.

For example, let’s print every 3rd number in an array of numbers:

```const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

var i = 0
const interval = 3

while (i < numbers.length) {
if (i % interval == 0) {
console.log(i)
}
i += 1
}```

Output:

```0
3
6
9
12```

## Conclusion

Today you learned how to calculate remainders in JavaScript.

To recap, in maths, a mod b calculates the remainder in the division between a and b. In other words, it calculates what is left after an even division.

For example, `7 mod 3` represents sharing 7 apples with 3 workers evenly. The result is 1. In other words, 1 apple is left over after sharing 7 apples with 3 persons evenly.

• To calculate modulo in JavaScript, use the modulo operator %.

Modulos also work for negative numbers in JavaScript. But the way negative modulos are calculated differs among programming languages.

There are many use cases for modulo in JavaScript.

For example, to figure out if a number is odd or even, you can use modulo. Or if you need to introduce periodicity in your code, you can take advantage of modular arithmetic.

Scroll to Top