Check Even or Odd

Program to check if a number is even or odd

BeginnerTopic: Conditional Programs
Back

JavaScript Check Even or Odd Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// Method 1: Using if-else
let number = 7;

if (number % 2 === 0) {
    console.log(number + " is even");
} else {
    console.log(number + " is odd");
}

// Method 2: Using ternary operator
let num = 8;
let result = (num % 2 === 0) ? "even" : "odd";
console.log(num + " is " + result);

// Method 3: Using function
function checkEvenOdd(n) {
    if (n % 2 === 0) {
        return "even";
    } else {
        return "odd";
    }
}

console.log("10 is " + checkEvenOdd(10));
console.log("15 is " + checkEvenOdd(15));
Output
7 is odd
8 is even
10 is even
15 is odd

Understanding Check Even or Odd

This program demonstrates conditional logic using the modulus operator.

Modulus Operator (%)

The modulus operator returns the remainder after division:

number % 2 === 0 → Even number
number % 2 === 1 → Odd number

If-Else Statement

Basic conditional structure:

if (condition) {
} else {

    // code if false
}
    // code if true

Ternary Operator

Shorthand for if-else:

condition ? valueIfTrue : valueIfFalse

Comparison Operators

===: Strict equality (checks value and type)
!==: Strict inequality
==: Loose equality (avoid, can cause bugs)
!=: Loose inequality (avoid)

Best Practice:

Always use === for equality checks!

Function Approach

Creating reusable function:

function checkEvenOdd(n) {
}
    return (n % 2 === 0) ? "even" : "odd";

Edge Cases

checkEvenOdd(0);   // "even"
checkEvenOdd(-2);  // "even"
checkEvenOdd(-3);  // "odd"

Let us now understand every line and the components of the above program.

Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.

Table of Contents