JavaScript(JS) JS check if a number is odd or even
In JavaScript, you can check if a number is odd or even by using the modulo operator %
. An even number divided by 2 will have a remainder of 0, whereas an odd number divided by 2 will have a remainder of 1. Here's an example:
const num = 5; if (num % 2 === 0) { console.log(`${num} is even.`); } else { console.log(`${num} is odd.`); }
In the above example, we first create a variable num
with the value of 5
. We then use the modulo operator %
to check if num
is even or odd. If num
is even (i.e., the remainder of num
divided by 2
is 0
), we log a message saying that num
is even. Otherwise, if num
is odd (i.e., the remainder of num
divided by 2
is 1
), we log a message saying that num
is odd.
You can replace the value of the num
variable with any other number to check if it is odd or even.