Skip to content

JavaScript modulo operator (%)

  • by

The JavaScript modulo operator (%) returns the remainder of a division operation. It can be used to check if a number is even or odd or to determine if a number is divisible by another number.

dividend % divisor

The syntax for the JavaScript modulo operator is as follows:

Copy codedividend % divisor

Here, the dividend is the number being divided, and the divisor is the number dividing the dividend. The operator % returns the remainder of this division operation.

console.log(10 % 3); // Outputs 1

In this example, the dividend is 10 and the divisor is 3. The modulo operator returns the remainder of 10 divided by 3, which is 1.

JavaScript modulo operator (%) Example

Simple example code using the modulo operator to check if a number is even or odd, or to determine if a number is divisible by another number.

<!DOCTYPE html>
<html>
  <body>
    <script>
    // Check if a number is even
    function isEven(number) {
        return number % 2 === 0;
    }

    console.log(isEven(4)); 
    console.log(isEven(5)); 

    // Check if a number is divisible by another number
    function isDivisible(number, divisor) {
        return number % divisor === 0;
    }

    console.log(isDivisible(10, 2));
    console.log(isDivisible(10, 3));

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

Output:

JavaScript modulo operator (%)

Comment if you have any doubts or suggestions on this JS Operator 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