How to Find a Remainder in JavaScript

Posted by

To find the remainder of a division operation in JavaScript, you can use the modulo operator (%). This operator returns the remainder of the division of two numbers.

Here’s an example of how to use the modulo operator to find the remainder of a division operation:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

// Find the remainder of 10 divided by 3
const remainder = 10 % 3;
console.log(remainder); // Output: 1

[/dm_code_snippet]

The modulo operator is often used in situations where you want to find out if a number is even or odd, by checking whether it is divisible by 2.

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

// Check if a number is even or odd
const number = 5;
if (number % 2 === 0) {
  console.log(`${number} is even`);
} else {
  console.log(`${number} is odd`);
}
// Output: "5 is odd"

[/dm_code_snippet]

You can also use the modulo operator to wrap a value around a range. For example, if you want to ensure that a number is always between 0 and 5 (inclusive), you can use the modulo operator to “wrap” the number back to the range if it goes outside of it.

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

// Wrap a number around a range
function wrap(num, min, max) {
  return ((num - min) % (max - min + 1)) + min;
}

console.log(wrap(3, 0, 5)); // Output: 3
console.log(wrap(8, 0, 5)); // Output: 3
console.log(wrap(-2, 0, 5)); // Output: 4

[/dm_code_snippet]