Javascript Modulo

Javascript Modulo

Javascript modulo is an operator represented by the % character. This operator returns the remainder of two numbers that need to be divided into javascript. There are a lot of arithmetic operations in Javascript such as addition, subtraction, multiplication, division, increment etc.

We use them mostly while performing the hash operations. This is because the remainder is always less than the divisor; hence it can restrict the range of the returned values. The number on which arithmetic operations are performed is called the operator of modulo. The operation which is to be performed on the two inputs is called the operand. The user can also use a modulo to convert the operands to unsigned 32-bit operator values.

The simple formula to calculate modulo of 2 numbers is:

modulo= a % b

where a is the dividend and b is the divisor. In case the inputs are string values, they are first converted into integer values. There are some key features about modulo operator that user should be aware of:

  • If the dividend input is 0, the output will be NOT a NUMBER.
  • When the user tries to divide infinity by infinity, the result will be NOT a NUMBER.
  • If the dividend is zero, the output will also be 0.
  • The output will be the dividend only if the user divided divisor input by an infinite number,

Javascript modulo Example

<!DOCTYPE html>
<html>
<body>
<h2>The / Operator</h2>
<p id="test"></p>
<script>
var a = 8;
var b = 3;
var c = a % b;
document.getElementById("test").innerHTML = c;
</script>
</body>
</html>

The output of this javascript program will be:

2

Difference between modulo operator and remainder operator:

  • If both the dividend and divisor are positive integers, modulo will give the output as the reminder operator in the arithmetic operations.
  • In case the dividend and divisor are not positive integers, modulo will give the different output from the remainder operator.
  • Modulo operator binds an arbitrary integer into a given range.

Hence, we conclude that the modulo operator in javascript will only work on the positive integers. In this can both the operators will work the same. Whereas both will work out their own ways in case the integers are negative. Hence, the modulo operator in javascript is just the remainder operator which will give negative output if the input is negative.

Leave a comment

Your email address will not be published.