We are going to learn how to check whether the number is even or Odd using JavaScript. In the number system, any natural number that can be expressed in the form of (2n + 1) is called an odd number, and if the number can be expressed in the form of 2n is called an even number.
- Even Examples : 2, 4, 6, 8, 10, ...
- Odd Examples : 1, 3, 5, 7, 9, ,,,
Here are the different approaches we can use in JavaScript to determine whether a number is odd or even:
1. Using the modulo Operator
The modulo operator gives the remainder when one number is divided by another. To check if a number is even or odd:
- If the result of N%2 is 0, the number is even.
- If the result is 1, the number is odd.
function isEven(n) {
return (n % 2 == 0);
}
let n = 101;
isEven(n) ? console.log("Even") : console.log("Odd");
Output
Odd
2. Using Bitwise & Operator
A faster way to check if a number is even or odd is by using the Bitwise AND Operator (&). This checks the last bit of a number.
- If the last bit is 1, the number is odd.
- If the last bit is 0, the number is even.
function checkOddOrEven(n) {
if (n & 1 == 1) {
return "Number is odd";
}
return "Number is even";
}
console.log(checkOddOrEven(12));
console.log(checkOddOrEven(121));
Output
Number is even Number is odd
3. Using Bitwise OR Operator (|)
The Bitwise OR Operator (|) compares two numbers bit by bit. It returns 1 for each bit position where at least one of the bits is 1. If both bits are 0, it returns 0. In simple words, the OR operator checks two bits and returns 1 if either of the bits is 1. If both bits are 0, it returns 0.
function checkOddOrEven(number) {
return (number | 1) === number ? 'Odd' : 'Even';
}
console.log(checkOddOrEven(14));
console.log(checkOddOrEven(17));
Output
Even Odd
4. Using if...else Statement
The if...else statement is a fundamental structure in JavaScript. It allows you to execute different blocks of code depending on whether a condition is true or false. This can be used to check if a number is odd or even.
let num = 4;
if (num % 2 === 0) {
console.log("The number is even.");
} else {
console.log("The number is odd.");
}
Output
The number is even.
5. Using the Ternary Operator
The Ternary Operator is a shorthand for the if...else statement. It takes three operands: a condition, a result for true, and a result for false. This can be used to check whether a number is even or odd in one line.
let num = 8;
let result = (num % 2 === 0) ? "The number is even." : "The number is odd.";
console.log(result);
Output
The number is even.