Check if a variable is divisible by 2 in JavaScript
In this tutorial, we are going to learn about how to check if a given variable is divisible by 2 or not in JavaScript with the help of examples.
Consider, we have a following variable:
const a = 10;To find if a above variable is divisible by 2 or not, the variable should be divided by 2 and the remainder should be 0.
Using % Modulo operator
To check if a variable is a divisible by 2 or not, we can use the % modulo operator in JavaScript.
The modulo % operator returns the remainder of the first number and second number like this
10 % 2 = 0, so if we get a remainder 0 then the given number is a divisible of another number. otherwise it is not a divisible of another number.
Here is an example:
const a = 10;
if (a % 2 === 0) {
  console.log("a is divisible by 2");
} else {
  console.log("a is not divisible by 2");
}Output:
"a is divisible by 2"In the above code, we have added the a % 10 === 0 in if condition, so if the variable a is divided by 2 and returns the remainder 0, then it logs the output “a is divisible by 2”, otherwise it logs "a is not divisible by 2".
Example 2 :
const b = 20;
if (b % 2 === 0) {
  console.log("b is divisible by 2");
} else {
  console.log("b is not divisible by 2");
}Output:
"b is divisible by 2"Checking if a number is not divisible by 2
To check if a number is not divisible by 2, we can use the modulo operator % but the remainder of first number by second number is not equal to 0.
Here is an example:
const c = 23;
if (c % 2 != 0){
    console.log("c is not divisible by 2");
}In the above code, 23 is divided by 2 and returns the remainder 3. So the given number is not a divisible of 2.


