Master JavaScript Programming From Scratch

Clear, interactive, and structured JavaScript lessons designed for absolute beginners.

If Else

Learn how JavaScript makes decisions using if, else if, and else statements.

What is if...else?

An if statement runs a block of code when a condition is true.

The optional else block runs when that condition is false. This allows a program to choose between different actions.

Basic Syntax

if (condition) {
    // code runs when condition is true
} else {
    // code runs when condition is false
}

How if...else Works

Condition → Decision → Execute One Branch
Input Value is received
→
Condition? true or false
TRUE Run the if block
FALSE Run the else block

else if

When more than two possible conditions exist, we can use else if to test additional conditions.

if

Checks the first condition.

else if

Checks another condition when the previous condition was false.

else

Runs when none of the previous conditions are true.

Example 1: Checking Pass or Fail

We can use an if...else statement to check whether a student's marks meet the passing requirement.

const marks = 68;

if (marks >= 40) {
    console.log("Student Passed");
} else {
    console.log("Student Failed");
}

Output

Student Passed

Example 2: Using else if

We can use multiple conditions to assign a result based on marks.

const marks = 82;

if (marks >= 90) {
    console.log("Grade A+");
} else if (marks >= 75) {
    console.log("Grade A");
} else if (marks >= 60) {
    console.log("Grade B");
} else if (marks >= 40) {
    console.log("Grade C");
} else {
    console.log("Fail");
}

Output

Grade A

Important Note

Conditions are checked in order

In an else if chain, JavaScript checks conditions from top to bottom.

When a condition becomes true, its block executes and the remaining else if and else blocks are skipped.

Summary

The if statement executes code when a condition is true. The else statement handles the false case, while else if allows multiple conditions to be checked in sequence. These statements are commonly used to make decisions in JavaScript programs.