Remainder / Modulus (%). One awesome article in 2021

The remainder / modulus operator (%) returns the remainder after (integer) division.

JS

console.log( 42 %  10); //  2
console.log( 42 % -10); //  2
console.log(-42 %  10); // -2
console.log(-42 % -10); // -2
console.log(-40 %  10); // -0
console.log( 40 %  10); //  0
Remainder / Modulus (%) output
Remainder / Modulus (%) output

For more, please watch the video:

This operator returns the remainder left over when one operand is divided by a second operand. When the first operand is a negative value, the return value will always be negative, and vice versa for positive values.

In the example above, 10 can be subtracted four times from 42 before there is not enough left to subtract again without it changing sign. The remainder is thus: 42 - 4 * 10 = 2.

The remainder operator may be useful for the following problems:

Test if an integer is (not) divisible by another number in Remainder / Modulus:

JS

 x % 4 == 0 // true if x is divisible by 4
 x % 2 == 0 // true if x is even number
 x % 2 != 0 // true if x is odd number

Since 0 === -0, this also works for x <= -0.

Implement cyclic increment/decrement of value within [0, n) interval in Remainder / Modulus.

Suppose that we need to increment integer value from 0 to (but not including) n, so the next value after n-1 become 0. This can be done by such pseudocode:

JS

var n = ...; // given n
var i = 0;
function inc() {
    i = (i + 1) % n;
}
while (true) {
    inc();
    // update something with i
}

Now generalize the above problem and suppose that we need to allow to both increment and decrement that value from 0 to (not including) n, so the next value after n-1 become 0 and the previous value before 0 become n-1.

JS

var n = ...; // given n
var i = 0;
function delta(d) { // d - any signed integer
    i = (i + d + n) % n; // we add n to (i+d) to ensure the sum is positive
}

Now we can call delta() function passing any integer, both positive and negative, as delta parameter.

Using modulus to obtain the fractional part of a number

JS

 var myNum = 10 / 4;       // 2.5
 var fraction = myNum % 1; // 0.5
 myNum = -20 / 7;          // -2.857142857142857
 fraction = myNum % 1;     // -0.857142857142857

Conclusion:

All examples on codepen

Just for fun, watch Best Fails compilation

Leave a Reply