Check if a variable is divisible by 2 in JavaScript

Check if a variable is divisible by 2 in JavaScript

In this post we will give you information about Check if a variable is divisible by 2 in JavaScript. Hear we will give you detail about Check if a variable is divisible by 2 in JavaScriptAnd how to use it also give you demo for it if it is necessary.

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 this10 % 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.

Hope this code and post will helped you for implement Check if a variable is divisible by 2 in JavaScript. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US