What is Modulus Operator (%) in JavaScript?

In some languages, the modulus operator is also known as the remainder operator. The remainder operator and the modulus operator both are used to get the remainder of an integer when it is divided by some other integer, but they are different from each other in case of signs of the remainder whether it has to be positive or negative that is returned after the division.

In the expression a % b, a is called dividend, while b is known as divisor. In case of the modulo, the expression ((a % b) + b) % b is used to find out the remainder, where the sign of the resultant remainder will be similar to the sign of the divisor, b in this case. While, the expression a % b can be used to find the remainder using the remainder operator, where the sign of the dividend such that a is considered as the sign of the remainder result. The operation a % b will return NaN in the following cases −

  • If any of the numbers is NaN.
  • If divisor or the denominator is Zero.

Syntax

Following is the syntax to use the modulus operator in JavaScript −

operand1 % operand2

It returns the remainder of an integer division of operand1 by operand2.

Let us understand the modulus operator in JavaScript in detail with help of a code example.

Example 1

You can try to run the following code to learn how to work with Modulus (%) operator.

<html>
<body>
   <script>
      var a = 33;
      var b = 10;

      document.write("a % b = ");
      result = a % b;
      document.write(result);
   </script>
</body>
</html>

Related Posts

What are custom events in JavaScript?

Custom events are the events that allow you to decouple the code you want to run after a specific piece of code runs. There are various in-built events…

How to use nested for loop in JavaScript?

We use the for loop statement of JavaScript for repeating a set of statements inside the loop body a specified number of times. A nested for loop, as the…

What are the basic rules for JavaScript parameters?

A JavaScript function is a code that performs a particular task. The function parameters are the name list in the function definition. Parameters are also known as…

How to stop refreshing the page on submit in JavaScript?

Using event.preventDefault() to stop page refresh on form submit In this section, we will see how to use event.preventDefault() to stop page refresh on form submission. The event.preventDefault() restricts the default…

Target a Window Using JavaScript or HTML

TARGET attribute of HTML A link’s opening named frame or window is specified using the Target attribute of the <a> anchor tag. The concluding </a> tag in…

What is the role of deferred scripts in JavaScript?

Since JavaScript is a loosely typed language, you are not required to correctly predict the kind of data that will be kept in a variable. Depending on the information…