JavaScript Program to Check if a Number is Odd or Even
Last Updated :
29 Nov, 2023
In this article, 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.
In other words, Those numbers that are completely divisible by 2 (give the remainder 0 after dividing by 2) are known as even numbers and those which divided by 2 and leave a reminder 1 are called odd numbers.
Even = {2k : k ∈ Z}
Odd = {2k + 1 : k ∈ Z}
where k is an integer.
Example:
Input: 2
Output: Even number
Input: 41
Output: Odd Number
There are several methods that can be used to Check if a Number is Odd or Even, which are listed below:
Approach 1: Using the modulo Operator
In this method, we use the JavaScript Modulo Operator (%) to check whether the number is even or odd in JavaScript. We will evaluate the N % 2, and if the result is 0 then the number is even otherwise the number is odd.
Syntax:
remainder = var1 % var2
Example: In this example, we are using the modulo operator to find given number is even or odd.
Javascript
function isEven(n) {
return (n % 2 == 0);
}
let n = 101;
isEven(n) ? console.log( "Even" ) : console.log( "Odd" );
|
A better solution is to use bitwise operators. We need to check whether the last bit is 1 or not. If the last bit is 1 then the number is odd, otherwise the number is even.
Syntax:
a & b
Example: In this example, we are using the bitwise & operator to find given number is even or odd.
Javascript
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
JavaScript Bitwise OR(|) Operator is used to compare two operands by performing OR operation on individual bits of the operands and returns true even if one of the compared bits is 1.
Syntax:
a | b
Example: In this example, we are using the bitwise OR operator to find whether our given number is even or odd.
Javascript
function checkOddOrEven(number) {
return (number | 1) === number ? 'Odd' : 'Even' ;
}
console.log(checkOddOrEven(14));
console.log(checkOddOrEven(17));
|
Ternary operator (?:) is a shorthand conditional operator that evaluates a condition and returns one of two expressions based on the result.
Syntax:
condition ? value if true : value if false
Example: In this example, we are using the Ternary operator to find given number is even or odd.
Javascript
function checkOddOrEven(num) {
return num % 2 === 0 ? 'Even' : 'Odd' ;
}
console.log(checkOddOrEven(21));
console.log(checkOddOrEven(12));
|
Share your thoughts in the comments
Please Login to comment...