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>