JavaScript Modulus Operator

JavaScript Modulus Operator | In the equation n%d, n is referred to as the dividend and d as the divisor. When one of the inputs is NaN, n is Infinity, or d is 0, the function returns NaN. Otherwise, the dividend n is returned if d is Infinity or if n is ±0.

The remainder r is determined as r:= n – d * q wherein q is the integer so that r has the same sign as the dividend n while being as near to 0 as possible. This formula is used when the operands are non-zero and finite. Be aware that while ‘%’ is typically a remainder operator in most languages (like Python and Perl), it is a modulo operator in others.

Modulo is described as k:= n – d * q, where q is an integer that is as close to 0 as possible with the same sign as the divisor d. When the operands have opposite symbols, the modulo result will always have the same sign as the divisor while the remainder will always have the same sign as the dividend. This can cause them to differ with one unit of d. In JavaScript, use ((n% d) + d)% d in place of n% d to get a modulo.

The modulo operation, which lacks a specific operator, is employed by JavaScript to normalize the second operand of bitwise shift operators (, >>, etc.), ensuring that the offset has always been positive.

JavaScript Modulus Operator Example

The remainder of a positive dividend:-

let num1 = 17 % 5;
console.log(num1); // 2

let num2 = 8 % -3;
console.log(num2); // 2

let num3 = 1 % 2;
console.log(num3); // 1

let num4 = 2 % 3
console.log(num4); // 2

let num5 = 5.5 % 2;
console.log(num5); // 1.5

Output:-

2
2
1
2
1.5

JavaScript Modulus Operator Example – Remainder with negative dividend:-

let num1 = -13 % 5;
console.log(num1); // -3

let num2 = -1 % 2;
console.log(num2); // -1

let num3 = -4 % 2;
console.log(num3); // 0

Output:-

-3
-1
-0

Remainder with NaN:-

let num1 = NaN % 2;
console.log(num1); // NaN

Output:-

NaN

Remainder with Infinity:-

let num1 = Infinity % 5;
console.log(num1); // NaN

let num2 = Infinity % 0;
console.log(num2); // NaN

let num3 = Infinity % Infinity;
console.log(num3); // NaN

Output:-

NaN
NaN
NaN

let num1 = 3 % Infinity;
console.log(num1); // 3

let num2 = 0 % Infinity;
console.log(num2); // 0

let num3 = -5 % Infinity;
console.log(num3); // -5

let num4 = 3 % -Infinity;
console.log(num4); // 3

let num5 = 0 % -Infinity;
console.log(num5); // 0

let num6 = -5 % -Infinity;
console.log(num6); // -5

Output:-

3
0
-5
3
0
-5

We can get the remaining of a value after dividing it by another value in JavaScript by using the remainder operator (%).

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *