Home Programs How to Check if a Number is Odd or Even in JavaScript

How to Check if a Number is Odd or Even in JavaScript

Even numbers are those numbers that are exactly divisible by 2.

The remainder operator % will give the remainder when used with a number.

Table of Contents

Example 1

// program to check if the number is even or odd
// take input from the user
const number = prompt("Enter a number: ");

//check if the number is even
if(number % 2 == 0) 
{
    console.log("The number is even.");
}
// if the number is odd
else 
{
    console.log("The number is odd.");
}

When you run this you will see something like this

And the output was

The number is odd.

Example 2

You can also use the ternary operator like this

// program to check if the number is even or odd
// take input from the user
const number = prompt("Enter a number: ");

// ternary operator
const result = (number % 2  == 0) ? "even" : "odd";

// display the result
console.log(`The number is ${result}.`);

You may also like