JavaScript Program to Check if a Number is Even or Odd

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

Introduction

Determining whether a number is even or odd is a basic and common operation in programming. A number is even if it is divisible by 2 with no remainder and odd if it leaves a remainder of 1 when divided by 2. This program will help check if a given number is even or odd.

Problem Statement

Create a JavaScript program that:

  • Accepts a number.
  • Checks whether the number is even or odd.
  • Displays the result indicating if the number is even or odd.

Example:

  • Input: 12

  • Output: 12 is an even number

  • Input: 7

  • Output: 7 is an odd number

Solution Steps

  1. Read the Input Number: Accept the number either from user input or directly within the code.
  2. Check Even or Odd: Use the modulus operator (%) to determine if the number is divisible by 2.
  3. Display the Result: Print whether the number is even or odd based on the result.

JavaScript Program

// JavaScript Program to Check if a Number is Even or Odd
// Author: https://www.javaguides.net/

function checkEvenOrOdd(number) {
    // Step 1: Check if the number is even or odd
    if (number % 2 === 0) {
        console.log(`${number} is an even number`);
    } else {
        console.log(`${number} is an odd number`);
    }
}

// Example input
let inputNumber = 12;
checkEvenOrOdd(inputNumber);

Output

12 is an even number

Example with Different Input

let inputNumber = 7;
checkEvenOrOdd(inputNumber);

Output:

7 is an odd number

Explanation

Step 1: Check if the Number is Even or Odd

  • The number is passed to the checkEvenOrOdd() function. The modulus operator (%) checks if there is any remainder when the number is divided by 2. If no remainder is left (number % 2 === 0), the number is even; otherwise, it is odd.

Step 2: Display the Result

  • The result is printed using console.log(), specifying whether the number is even or odd.

Conclusion

This JavaScript program demonstrates how to check whether a number is even or odd using the modulus (%) operator. This simple task is essential for various logic operations in programming, helping developers handle conditional checks based on numerical properties.

My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare