Check Whether a Number is Even or Odd in Javascript
We will discuss two method to solve this problem
Introduction
Hi everyone In this article we will create a javascript program to check number is Even or Odd in Javascript. To achieve this, divide the number by 2, then determine if it is divisible or not. If a number is exactly divisible by 2, it is an even number; otherwise, it is an odd number.
Here are the Methods to solve the above-mentioned problem,
Method 1: Using Brute Force
Method 2: Using Ternary Operator
Flow Chart
Method: 1 Using Brute Force
This method simply checks if the given input integer is divisible by 2 or not. If it’s divisible then print Even or Odd otherwise.
Algorithm
step 1: Input Number
step 2: check whether the number is divisible by 2
step 3: if(number % 2 == 0)
if yes print "Even Number"
if no print "Odd Number"
step 4: stop
Javascript Code
//method 1 Brute Force
let number = 20;
if(number %2 == 0){
console.log(`${number} is Even Number`);
}else{
console.log(`${number} is Odd Number`);
}
Output
20 is Even Number
Method: 2 Using Ternary Operator
This Method uses the ternary operator to check if the integer input is divisible by 2, If true print Even or Odd otherwise.
Syntax:
(condition) ? (if True : Action) : (if false : Action);
Algorithm
step 1: Input Number
step 2: check whether the number is divisible by 2 or not using the ternary operator
step 3: (number % 2) ? ("Even number") : ("Odd number")
step 4: stop
Javascript Code
//Method 2 ternary operator
let number2 = 21;
let result = number2% 2 == 0 ? ' is Even Number': ' is Odd Number';
console.log(number2+result)
Output
21 is Odd Number