Signup/Sign In
PUBLISHED ON: MARCH 13, 2023

JavaScript Program to Check if a Number is Odd or Even

In this tutorial, we'll learn how to make a JavaScript program that checks if a given number is odd or even. Finding the parity of a number is a simple operation that is often used in math and computer programming. It's an easy job that can be done with a few lines of code.

We'll use the modulo operator (%), which gives us the remainder of a division, to see if a number is odd or even. The number is even if the remainder is 0. If not, it seems strange.

First, we'll make a function that takes a number as an argument and gives back a string that says whether the number is odd or even. Then, we'll use a few examples to test our function and make sure it works the way it should.

We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.

Approach

The main idea of this program is to find whether the number is Even or Odd.

Even Numbers are those that are divisible by 2. We may also say an even number when divided by 2 gives the remainder as 0.

JavaScript Program to Check if a Number is Odd or Even

// Program in JavaScript to check if the number is even or odd
const num = prompt("Enter a number: ");

//check if the number is even
if(num % 2 == 0) 
    console.log("The number is Even.");

// if the number is odd
else 
    console.log("The number is odd.");


Enter a number: 677
The number is odd.

Using Ternary Operator

// JavaScript program to check if the number is even or odd

const number = prompt("Enter a number: ");

// ternary operator
const res = (number % 2  == 0) ? "Even" : "Odd";

console.log("The number is :" , res);


Enter a number: 15
The number is Odd.

Conclusion

In the end, we've learned how to make a JavaScript program that checks if a given number is odd or even. By using the modulo operator, we were able to figure out the parity of the number we were given and give the right answer. This program can help us do basic math and make decisions based on the parity of a number. It's a simple tool that can help us solve problems and write code that works better.



About the author:
Proficient in the creation of websites. Expertise in Java script and C#. Discussing the latest developments in these areas and providing tutorials on how to use them.