How to Use the Modulus Operator in JavaScript?

Estimated read time 1 min read

The modulus operator (%) in JavaScript returns the remainder of the division of one number by another. For example:

var dividend = 11;
var divisor = 4;
var result = dividend % divisor;
console.log(result); // Output: 3

In the example above, the modulus operator % is used to find the remainder of the division of 11 by 4. The result is 3, which means that 11 divided by 4 has a remainder of 3.

The modulus operator is commonly used to perform operations like checking if a number is odd or even, finding the cycle of a repeating pattern, or wrapping a value within a range.

Here’s an example that uses the modulus operator to check if a number is odd or even:

var number = 7;
if (number % 2 === 0) {
  console.log("The number is even");
} else {
  console.log("The number is odd");
}
// Output: The number is odd

In the example above, the modulus operator % is used to divide number by 2 and check if the remainder is equal to 0. If the remainder is equal to 0, then the number is even and the message “The number is even” is logged to the console. Otherwise, the number is odd and the message “The number is odd” is logged to the console.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply