We can use JavaScript to check if a number is divisible by another number by using the JavaScript built-in remainder operator %. If the remainder after division is 0, then the number is divisible by the number you divided by.


if ((x % y) == 0){
  return true; //number is divisible by other number
} else { 
  return false; //number is NOT divisible by other number
}

We can wrap this code and create our own simple function that takes two numbers. The first number will be the one we want to divide by the second one. Here is the our function:

function isDivisible(num1, num2){
  if ((num1 % num2) == 0){
    return true;
  } else { 
    return false;
  }
};

When working with numbers in JavaScript, it can be useful to know if the numbers you are working with are divisible by certain numbers.

We can use the JavaScript built-in remainder operator % to get the remainder of a number after division.

If the remainder after division is 0, then the number is divisible by the number you divided by.

Below is our function again. We will add some test examples to see what the function will return.

function isDivisible(num1, num2){
  if ((num1 % num2) == 0){
    return true;
  } else { 
    return false;
  }
};

console.log(isDivisible(10,2));
console.log(isDivisible(15,6));
console.log(isDivisible(167225,25));
console.log(isDivisible(-4,-2));

#Output:
true
false
true
true

How to Check if a Number is Divisible by Another Number

Using the JavaScript remainder operator %, we can determine if a number is divisible by any other number.

For example, to check if a number is divisible by 2 using JavaScript, we divide by 2. If the remainder after division is 0, then the number is divisible by 2. If it is not 0, then the number is not divisible by 2.

Below is a function which will check if a number is divisible by 2 in JavaScript.

function isDivisibleBy2(num){
  if ((num % 2) == 0){
    return true;
  } else { 
    return false;
  }
};

console.log(isDivisibleBy2(10));
console.log(isDivisibleBy2(15));

#Output:
true
false

If we want to check if a number is divisible by 3, just put 3 after the % operator in our function above.

function isDivisibleBy3(num){
  if ((num % 3) == 0){
    return true;
  } else { 
    return false;
  }
};

console.log(isDivisibleBy3(10));
console.log(isDivisibleBy3(15));

#Output:
false
true

How to Check if a Number is Even or Odd Using JavaScript

We can also use % to check if a number is even or odd very easily with the JavaScript built in remainder operator %. If the remainder of a number after dividing by 2 is 0, then the number is even. If not, the number is odd.

function isEven(num){
    if ((num % 2) == 0){
    return true;
  } else { 
    return false;
  }
};

console.log(isEven(10));
console.log(isEven(15));

#Output:
true
false

Hopefully this article has been useful for you to learn how to use JavaScript to check if a number is divisible by another.

Categorized in:

JavaScript,

Last Update: March 22, 2024