JavaScript Arithmetic (Math) Remainder / Modulus (%)

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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

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

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:

  1. Test if an integer is (not) divisible by another number:

     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.

  2. Implement cyclic increment/decrement of value within [0, n) interval.

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:

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.

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

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


Got any JavaScript Question?