Description
A Program to Check if a Number is Odd or Even
In this JavaScript lesson, we will practice how to write a program to check if a number is odd or even using a condition/decision-making statement and ternary operator.
Practice A: Check Even or Odd Number using if-else Condition
// Request user to insert a number const num = prompt("Enter any number: "); //check for even numberif(num % 2 == 0) { console.log("This is an even number."); } // check for odd number else { console.log("This is an odd number."); }
Output
Enter any number: 9 This is an odd number.
The program was executed successfully with the help of the condition statement, num % 2 == 0. This statement checks if the number entered by the user is even, odd, or zero. When the remainder = 0, the number entered is an even number. Else the number is an odd number.
Even numbers are numbers that are divisible by 2 without remainder or remainder = 0.
The modulus operator % returns only the remainder when used with a number. See the example below,
const num = 8; const output = num % 2; // remainder is 0
Note that when % is used with 2 and the remainder is equal to zero (0), the number is an even number. Else, the number is an odd number.
Practice B: Check Even or Odd Number using Ternary Operator
The ternary operator is a JavaScript operator which takes three operands rather than the typical one or two that most operators use. It provides a way to shorten a simple if-else block in JavaScript programs. Let’s quickly look at the example below.
// Request input from user const num = prompt("Enter any number: "); // apply ternary operator const output = (num % 2 == 0) ? "even" : "odd"; // display result on console console.log(`This is an ${output} number.`);
Output
Enter any number: 7 This is an odd number.
Ternary operators make JavaScript statements more concise, shortened, and easy to use. This is also applicable in other programming languages. As a beginner, the syntax may be new to you and the operator may seem a little confusing at the moment. Play more with it and you will get better as you go on writing JavaScript programs.
Rupika Dalpati (verified purchase)
Friendly projects for beginners. Very helpful.