JavaScript: Check if a Number is Even or Odd

1. Introduction

Determining whether a number is even or odd is one of the quintessential tasks in the world of programming, particularly for beginners. The task serves as an excellent introduction to conditional statements. In this post, we'll explore a simple JavaScript program that checks if a given number is even or odd.

2. Program Overview

In this guide, we will:

1. Declare a number.

2. Use the modulus operator to check the remainder when the number is divided by 2.

3. Based on the remainder, ascertain if the number is even or odd.

4. Display the result.

3. Code Program

let number = 15;   // Number to be checked
let result;        // To store the result (Even/Odd)

// Checking if the number is even or odd using modulus operator
if (number % 2 === 0) {
    result = "Even";
} else {
    result = "Odd";

console.log("The number " + number + " is " + result + ".");


The number 15 is Odd.

4. Step By Step Explanation

1. Variable Declaration: We start off by declaring a variable named number with a value of 15. This is the number we wish to check. Additionally, a result variable is declared to store the outcome.

2. Using the Modulus Operator: The modulus operator (%) returns the remainder when one number is divided by another. If a number has a remainder of 0 when divided by 2, it's even. Otherwise, it's odd.

3. Conditional Check: The if-else statement checks the condition (number % 2 === 0). If true, result is assigned the value "Even"; if false, "Odd".

4. Output the Result: The final step is to use the console.log function to display the outcome. Through concatenation, the output provides a coherent statement about the number's nature.