Skip to content

JavaScript modulus negative

  • by

In JavaScript, the modulus operator % returns the remainder of a division operation. When the dividend (the number being divided) is negative, the result of the modulus operation can be a bit confusing.

The modulus operator in JavaScript follows the sign of the dividend, which means that if the dividend is negative, the result will also be negative. Here’s an example:

-10 % 3 // returns -1

We can add our own modulo method to JavaScript which always gives the right answer rather than getting it wrong the way JavaScript does for negative numbers.


Number.prototype.mod = function(n) {
    return ((this%n)+n)%n;
}

JavaScript modulus negative example

Simple example code of how you could use the mod the method in a complete JavaScript code:

<!DOCTYPE html>
<html>
  <body>
    <script>
    // Define the mod method on Number.prototype
    Number.prototype.mod = function(n) {
        return ((this % n) + n) % n;
    }

    let x = 7;
    let y = -7;
    let z = 12.5;

    console.log(x.mod(3)); 
    console.log(y.mod(3)); 
    console.log(z.mod(5)); 
    
    // Use the mod method in a conditional statement
    if (x.mod(2) === 0) {
        console.log("x is even");
    } else {
        console.log("x is odd");
    }

    </script>
  </body>
</html>

Output:

JavaScript modulus negative

We also use the mod method in a conditional statement to check if x is even or odd.

Comment if you have any doubts or suggestions on this JS module topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading