TOC

The community is working on translating this tutorial into Uzbek, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Operators:

Remainder operator

The remainder operator is used to divide two numbers, but instead of returning the result as a floating point number (e.g. 5 / 2 = 2.5) it will do the calculation based only on whole numbers (integers) and return the remaining part (if any).

This might sound complicated, but let's have a look at a couple of examples to illustrate how it works. The remainder operator in JavaScript is a percentage sign, so instead of using the division operator (/) you will use the remainder operator (%), like this:

let n1 = 12, n2 = 5;
alert(n1 % n2);

The result of this operation will be 2. Why? Because when we try to do whole number division with 12 and 2, the closest number that can be divided equally by 5 is 10. The remaining part from 12 to 10 is 2, which will be returned when we use the remainder operator.

If we do it with 14 and 5, the result will be 4:

let n1 = 14, n2 = 5;
alert(n1 % n2);

But if we do it with 15 and 5, the result will be 0, because 15 and 5 are divisible:

let n1 = 15, n2 = 5;
alert(n1 % n2);

The remainder operator and zebra stripes

A little fun fact about the remainder operator is that its very commonly used to create so-called zebra stripes, where you give every second line another color, making it easier to read the lines. So when you print all the lines in a loop, you use the remainder operator to know whether you are currently outputting an even or an odd row and then you can use a proper CSS class or style to give color accordingly.

I don't want to get into the visual details of the zebra stripes, but as mentioned, it's all about figuring out whether we're at an even or an odd number, so let's look into an example that shows the concept of this and can easily be modified to work in any way you want it to:

for(let i = 1; i <= 10; i++)
{
	let isEven = (i % 2 == 0);
	document.write("Line " + i + " (" + (isEven ? "even" : "odd") + ")");
}

The remainder assignment operator: %=

JavaScript also comes with a remainder assignment operator, acting as a shortcut to assigning the result of the remainder operation to the left part of the operation:

let n1 = 12, n2 = 5;
n1 %= n2;
alert(n1);

Notice now that the n1 variable will hold the result of the operation, in this case 2.

Summary

The remainder (%) operator will return the remainder left over when one number is divided by another number. It can be used in many different situations, e.g. to check whether a number is even or odd.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!