By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript Program > Write a program to Check if a Number is Odd or Even in JavaScript
JavaScript Program

Write a program to Check if a Number is Odd or Even in JavaScript

Rocoderes
Last updated: 2022/09/08 at 6:27 PM
Rocoderes
Share
7 Min Read
Write a program to Check if a Number is Odd or Even in JavaScript

In this article, we will create a program to check if a number is odd or even using JavaScript. In this we will fetch the value given by the user, and we will check the number if it is odd or even using some basic logic. We will make this program using two methods:

Contents
Using If Else StatementIf Else Program Using User’s InputUsing Ternary OperatorTernary Program Using User’s InputYou may also like:
  • Using the if else statement
  • Using ternary operator

This is going to be a very easy and simple program, so let’s just make it with these two methods.

Using If Else Statement

So firstly, we will make our HTML markup, then we have added our <script> tag in which we will write this program. So if you’re unaware with if….else statement, then let’s take a reminder that it is a conditional statement. If the condition becomes true, then it simply executes the code written inside the if statement. And if the condition becomes false, then the code written in the if statement will be skipped and move to next statement like on else statement. Simply if condition is true then executes the code and if condition is wrong then else will be executed.

In JS code, we have declared a variable x with some initial value. Then we have added if statement in which we are checking the condition x%2==0, here ‘%’ operator returns the remainder of division of x%2. If remainder will be 0 then the value will be even, because we know that if we divide any value with 2 returns 0 remainder then that value will be even. Like 10%2, 24%2 etc.
We have added a <h1> with the message that number is even. If the condition is false then else part will be executed in which we have a message to print number is odd.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <script type="text/javascript">
        var x = 62;
        if(x % 2 ==0){
            document.write(`<h1> ${x} is an even number</h1>`);
        }
        else{
            document.write(`<h1> ${x} is an odd number</h1>`);
        }

        
    </script>
</body>
</html>
Write a program to Check if a Number is Odd or Even in JavaScript

If Else Program Using User’s Input

Okay, we have created the code to understand basic logic of our if…else program. Now we will get the value from the user and check it.

Here, as you can see, program logic is common, but we have added an input field in which we will get the value from the user. And also added a button on which we have added an event listener to listen the click. So if the button gets clicked, then we will call a function named “get”.

We have defined this function inside the JS Code. In this function, we have added a variable in which we have stored the value from the input field. Here, we have used the document.querySelector() method to fetch the input field element from DOM, and used the value attribute to fetch the value from the input field. Then after, we have just added the same condition as above to check number’s property.

Here a question is raised like what do we need to check 2 or more conditions? So the answer is, you can check the second condition with the help of the else if statement. You can read more about it here.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="number"/>
    <button onclick= get()>Click me</button>

    <script type="text/javascript">
      function get() {
        var x = document.querySelector('input').value;
        if (x % 2 == 0) {
          document.write(`<h1> ${x} is an even number</h1>`);
        } else {
          document.write(`<h1> ${x} is an odd number</h1>`);
        }
      }
    </script>
  </body>
</html>

Using Ternary Operator

Ternary operator is pretty much straight forward and has less code than the if else statement. The syntax for ternary operator is condition? true: false. So here we will condition if the condition is right than the first statement which is next to question mark will be executed. And if it is wrong, then the second statement which is next to the colon sign.

Now, here we have declared a variable with some random value. Then we have declared another variable in which we have checked the condition if it is true then we will add a string “even”, and if it is false then we will add a string “odd”.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>

    <script type="text/javascript">
      var x = 211
      var res = x % 2 == 0 ? "even": "odd";
      document.write(`<h1>${x} is an ${res} number`)
      </script>
  </body>
</html>
Write a program to Check if a Number is Odd or Even in JavaScript

Ternary Program Using User’s Input

Similar to the If else statement code, we kept the main logic as it is, and we have added an input field along with a button on which we have an onclick event listener with a function call. We have just declared this function in our JS code. In this function, we have fetched the input field using document.querySelector method and used value attribute to get the value from that input.

Then we have applied the same logic to check number’s property.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="number" />
    <button onclick=get()>Click Me</button>

    <script type="text/javascript">
      function get(){
        var x = document.querySelector("input").value;
        var res = x % 2 == 0 ? "even": "odd";
        document.write(`<h1>${x} is an ${res} number`)
      }
    </script>
  </body>
</html>

You may also like:

  • How to Check If a Number is Positive, Negative, or Zero
  • How to Convert Kilometers to Miles and Celsius to Fahrenheit
  • How to Add Two Numbers, Swap Two Numbers And Find Square Root in JavaScript

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

TAGGED: programs
Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Posted by Rocoderes
Rocoderes is a blog you can learn HTML, CSS, JavaScript, React Js and Python along with creative coding stuff and free source code files.
Previous Article Write a Proram to Generate a Random Number in JavaScript Write a Proram to Generate a Random Number in JavaScript
Next Article Write a Program to Check If a Number is a Prime Number or Not in JavaScript Write a Program to Check If a Number is a Prime Number or Not in JavaScript
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

Computing Fibonacci Sequence in JavaScript

Computing Fibonacci Sequence in JavaScript

January 12, 2023
Swap Two Numbers Without A Third Variable

How to Swap Two Numbers Without A Third Variable in JS

December 12, 2022
Armstrong Number

How to Find an Armstrong Number Using JavaScript

September 23, 2022
Print The Table

How to Print The Table of Any User Defined Number Using Function

September 22, 2022
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?