The Modulus (Remainder) Operator in JavaScript

The modulus operator in JavaScript, also known as the remainder operator returns the remainder of a division. In this tutorial, we will learn how this operator works with examples.

 

The Modulus Operator Syntax

The remainder operator divides the number on the left of a % (percent) by a number on the right and returns the result.

 

console.log(14 % 3)
2

 

console.log(15 % 3)
0

 

console.log(16 % 3)
1

 

When the first number supplied is negative, the result returned will always be negative:

 

console.log(-16 % 3)
-1

 

Check if Even In JavaScript

To find if a number is even we can check if the remainder of the modulus operator result is 0 when the divider is 2.

 

number = 6

result = number % 2 == 0;

if (result) {
  console.log(number +' is even');
} else {
  console.log(number +' is not even');
}
6 is even

 

Check if Odd in JavaScript

To see if a number is odd we can check if the remainder of the modulus operator is not equal to 0 when the divider is 2.

 

number = 5

result = number % 2 !== 0;

if (result) {
  console.log(number +' is not even');
} else {
  console.log(number +' is even');
}
5 is not even

 

Displaying Every Second Value

Now we know that the JavaScript modulus operator will give us the remainder of two divided numbers, we can use it to find out if a number is divisible by another. This can be useful for doing something every n iterations in a for loop. Let's say we had an array of items and we only wanted to print every third value, we could use the remainder operator like this:

 

fruit = ['apple', 'strawberry', 'peach', 'apricot', 'orange'];

for (let i in fruit) {

  if (i % 3 == 0) {
    console.log(fruit[i])
  }
}
apple
apricot

 

In the example above if i divided by 3 has the remainder of 0, i must be 0 or a number in the 3 times table. Therefore we can use this result in an if statement to make something happen only every third iteration.

 

Conclusion

You now know how to get the remainder of a division is JavaScript using the modulus operator.

 

divide