Nicks Blog Site

Modulo Operator

What is the modulo operator?

The modulo operator is represented by the % character in JavaScript. It returns the remainder of two integers that have been divided. As the remainder will always be less than the divisor, modulo operators can be very useful in restricting the range of outputs. This makes modulo operators particularly popular in Hash functions (a function that takes input and produces an output of a fixed data).

Here are some code examples to try

Example 1

Shows the remainder

remainder = 15 % 2
console.log("The remainder is: " + remainder)

Example 2

Shows the remainder of the current number divided by 4

for(var i=0; i<10; i+=1){
  console.log( i % 4 )
}

Example 3

Shows if the number is even or odd

    const isEven = (number)=>{
      if(number % 2 == 0){
          return true;
      }else{
          return false;
      }
    }
    console.log(isEven(2));
    console.log(isEven(3));