Last updated: Mar 2, 2024
Reading timeยท2 min
Use the modulo %
operator to check if one number is a multiple of another
number.
The operator returns the remainder when one number is divided by another number. The remainder will only be zero if the first number is a multiple of the second.
const num1 = 15; const num2 = 5; const remainder = num1 % num2; console.log(remainder); // ๐๏ธ 0 if (remainder === 0) { // โ This runs console.log('๐๏ธ num1 is a multiple of num2'); } else { console.log('โ๏ธ num1 is NOT a multiple of num2'); }
We used the modulo operator to get the remainder of dividing one number by another.
0
, then the first number is a multiple of the second.Here are some more examples of using the modulo %
operator.
console.log(13 % 5); // ๐๏ธ 3 console.log(12 % 5); // ๐๏ธ 2 console.log(11 % 5); // ๐๏ธ 1 console.log(10 % 5); // ๐๏ธ 0
The number 10
is a multiple of 5
, so the division has a remainder of 0
.
The modulo %
operator always takes the sign of the first number (the
dividend).
console.log(-13 % 5); // ๐๏ธ -3 console.log(12 % -5); // ๐๏ธ 2
You might be wondering what happens if we get a remainder of -0
.
Would the if
condition fail because we only check for 0
.
console.log(-15 % 3); // ๐๏ธ -0
However, 0
is equal to -0
in JavaScript so our condition would still work.
console.log(0 === -0); // ๐๏ธ true
If you need to check if a number is a multiple of another number often, extract the logic into a reusable function.
function checkIfMultiple(num1, num2) { return num1 % num2 === 0; } console.log(checkIfMultiple(15, 5)); // ๐๏ธ true console.log(checkIfMultiple(15, 4)); // ๐๏ธ false console.log(checkIfMultiple(15, 3)); // ๐๏ธ true if (checkIfMultiple(15, 5)) { // โ This runs console.log('๐๏ธ num1 is a multiple of num2'); } else { console.log('โ๏ธ num1 is NOT a multiple of num2'); }
The checkIfMultiple()
function takes 2 numbers as parameters and checks if the
first number is a multiple of the second.
If you need to check if a number is not a multiple of another number, check if there is a remainder after using the modulo operator.
function checkIfNotMultiple(num1, num2) { return num1 % num2 !== 0; } console.log(checkIfNotMultiple(15, 5)); // ๐๏ธ false console.log(checkIfNotMultiple(15, 4)); // ๐๏ธ true console.log(checkIfNotMultiple(15, 3)); // ๐๏ธ false if (checkIfNotMultiple(15, 5)) { console.log('โ๏ธ num1 is NOT a multiple of num2'); } else { // โ This runs console.log('๐๏ธ num1 is a multiple of num2'); }
The checkIfNotMultiple()
function takes 2 numbers as parameters and checks if
the first number is not a multiple of the second.