# How to Use the Modulo (%) Operator in JavaScript?

Estimated read time 2 min read

The modulo operator (`%`) in JavaScript returns the remainder of a division operation. It’s commonly used to perform operations like finding the cycle of a repeating pattern, checking if a number is odd or even, or wrapping a value within a range.

Here’s an example that uses the modulo 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 modulo 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.

Here’s another example that uses the modulo operator to wrap a value within a range:

``````var value = 15;
var range = 10;
var wrappedValue = value % range;
console.log(wrappedValue); // Output: 5``````

In the example above, the modulo operator `%` is used to divide `value` by `range` and find the remainder. The result, `5`, is the wrapped value that is within the range `0` to `9`.

Add yours