To tell if a Number in JavaScript is even or odd, we can use the modulus (remainder) operator % along with an if conditional statement.

if ((num % 2) == 0){
  //Number is Even
} else {
  //Number is Odd
}

If the remainder of a number after dividing by 2 is 0, then the number is even. If not, the number is odd.

We can also check if a number is odd using the operator %. If the remainder of a number after dividing by 2 is 1, then the number is odd.

if ((num % 2) == 0){
  //Number is Even
}
if ((num % 2) == 1){
  //Number is Odd
}

Tell if a Number in JavaScript is Even or Odd with a Click

Below we will provide code to let the user input a number, and then use the % operator to tell if the number is even or odd. Here is our simple HTML setup:

Type a whole number to know if it's even or odd:

Get results

First, we will add an onclick event to the submit button to run a function we will create.

We will then use the value property along with the getElementById method to get the value of the input.

We will then determine if the number is even or odd using the code we have above.

Finally, we will display the results using the textContent property.

function evenOrOdd(){
  
  //Get the user input
  var userInput = Number(document.getElementById("userVal").value);

  //Check if the number is even or odd and display results
  if ((userInput % 2) == 0){
    document.getElementById("results").textContent = "The Number is Even";
  } else if ((userInput % 2) == 1){
    document.getElementById("results").textContent = "The Number is Odd";
  } else {
    document.getElementById("results").textContent = "NaN";
  }
}

The final code and output for this example are below:

Code Output:

Type a whole number to know if it’s even or odd:

Get results

Full Code:

Type a whole number to know if it's even or odd:

Get results
<script> function evenOrOdd(){ var userInput = Number(document.getElementById("userVal").value); if ((userInput % 2) == 0){ document.getElementById("results").textContent = "The Number is Even"; } else if ((userInput % 2) == 1){ document.getElementById("results").textContent = "The Number is Odd"; } else { document.getElementById("results").textContent = "NaN"; } } </script>

Hopefully this article has been useful in helping you tell if a number in JavaScript is even or odd.

Categorized in:

JavaScript,

Last Update: March 15, 2024