# Control Flow in JavaScript: If, Else, and Switch Explained

## **Introduction**

Imagine you are standing at a crossroad in Delhi. You need to decide which direction to go based on where you want to go. If you want to go to the Taj Mahal, you take one road. If you want to go to the Red Fort, you take another road. If you want to go somewhere else, you take a third road. This decision-making process is called control flow.

In programming, control flow means deciding which code should run based on certain conditions. In this blog, we will learn about the most important control flow tools in JavaScript: `if`, `else`, `else if`, and `switch` statements.

* * *

## **1\. What Control Flow Means in Programming**

Control flow is the order in which your code runs. By default, JavaScript reads and executes code from top to bottom, line by line. However, sometimes you want your code to make decisions and run different code based on different situations.

### **Why Do We Need Control Flow?**

Think about a college admission system. The program needs to check:

*   Is the student's score above 80? If yes, admit them.
    
*   Is the student's score between 70 and 80? If yes, put them on the waiting list.
    
*   Is the student's score below 70? If yes, reject them.
    

Without control flow statements, you cannot make these decisions. Your code would just run the same way every time, which is not useful.

### **Real-Life Example**

Let's imagine Rahul is checking the weather before going to college:

*   If it is raining, he takes an umbrella
    
*   If it is sunny, he applies sunscreen
    
*   If it is cold, he wears a jacket
    

This is control flow in real life. In JavaScript, we use statements like `if`, `else`, and `switch` to make these kinds of decisions.

* * *

## **2\. The if Statement**

The `if` statement is the simplest control flow tool. It runs a block of code only if a certain condition is true.

### **Syntax**

```javascript
if (condition) {
  // Code runs only if condition is true
}
```

### **How It Works**

The condition is checked. If it is true, the code inside the curly braces runs. If it is false, the code is skipped.

### **Simple Examples**

#### **Example 1: Checking Age**

```javascript
let age = 18;

if (age >= 18) {
  console.log("You are eligible to vote");
}
```

Output: `You are eligible to vote`

In this example, the condition `age >= 18` is true, so the message is printed.

#### **Example 2: Checking Marks**

```javascript
let marks = 50;

if (marks >= 40) {
  console.log("Congratulations! You passed the exam");
}
```

Output: `Congratulations! You passed the exam`

#### **Example 3: When Condition Is False**

```javascript
let marks = 35;

if (marks >= 40) {
  console.log("Congratulations! You passed the exam");
}

console.log("This line always runs");
```

Output:

```plaintext
This line always runs
```

Notice that the congratulations message did not print because the condition was false. However, the code after the `if` statement still ran.

### **Step-by-Step Execution**

Let's trace through how the code runs:

```javascript
let studentScore = 75;

if (studentScore > 70) {
  console.log("Great performance!");
}

console.log("Thank you for taking the test");
```

Step 1: Variable `studentScore` is created with value 75

Step 2: Check the condition: Is 75 > 70? Yes, it is true

Step 3: Run the code inside the if block: Print "Great performance!"

Step 4: Move to the next line after the if block Step 5: Print "Thank you for taking the test"

Final Output:

```plaintext
Great performance!
Thank you for taking the test
```

* * *

## **3\. The if-else Statement**

The `if-else` statement lets you run one block of code if a condition is true, and a different block if the condition is false. It is like saying "Do this if true, otherwise do that".

### **Syntax**

```javascript
if (condition) {
  // Code runs if condition is true
} else {
  // Code runs if condition is false
}
```

### **How It Works**

The program checks the condition. If true, it runs the first block. If false, it runs the second block. Only one of the two blocks will run, never both.

### **Simple Examples**

#### **Example 1: Checking if You Can Vote**

```javascript
let age = 16;

if (age >= 18) {
  console.log("You can vote");
} else {
  console.log("You are too young to vote");
}
```

Output: `You are too young to vote`

Since 16 is not greater than or equal to 18, the condition is false, and the else block runs.

#### **Example 2: Checking if a Number Is Even or Odd**

```javascript
let number = 7;

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

Output: `The number is odd`

The remainder of 7 divided by 2 is 1 (not 0), so the condition is false, and we go to the else block.

### **Step-by-Step Execution**

Let's trace through another example:

```javascript
let temperature = 15;

if (temperature > 20) {
  console.log("It is warm outside");
} else {
  console.log("It is cold outside");
}
```

Step 1: Variable `temperature` is created with value 15

Step 2: Check the condition: Is 15 > 20? No, it is false

Step 3: Since the condition is false, skip the if block

Step 4: Run the else block: Print "It is cold outside"

Final Output:

```plaintext
It is cold outside
```

* * *

## **4\. The else if Ladder**

Sometimes you have more than two options. You want to check multiple conditions in order. The `else if` statement lets you do this. It is like saying "If this, do this. Else if that, do that. Else if something else, do something else. Otherwise, do this final thing".

### **Syntax**

```javascript
if (condition1) {
  // Code runs if condition1 is true
} else if (condition2) {
  // Code runs if condition1 is false and condition2 is true
} else if (condition3) {
  // Code runs if condition1 and condition2 are false and condition3 is true
} else {
  // Code runs if all conditions are false
}
```

### **How It Works**

JavaScript checks conditions from top to bottom. As soon as it finds a condition that is true, it runs that block and stops checking the remaining conditions. If no conditions are true, the final else block runs.

### **Simple Examples**

#### **Example 1: Checking College Grades**

```javascript
let score = 75;

if (score >= 90) {
  console.log("Grade: A");
} else if (score >= 80) {
  console.log("Grade: B");
} else if (score >= 70) {
  console.log("Grade: C");
} else if (score >= 60) {
  console.log("Grade: D");
} else {
  console.log("Grade: F (Fail)");
}
```

Output: `Grade: C`

The score 75 is:

*   Not >= 90, so skip the first block
    
*   Not >= 80, so skip the second block
    
*   Yes >= 70, so run this block and print "Grade: C"
    
*   Stop checking remaining conditions
    

#### **Example 2: Checking Time of Day**

```javascript
let hour = 14; // 2 PM

if (hour < 12) {
  console.log("Good morning!");
} else if (hour < 17) {
  console.log("Good afternoon!");
} else if (hour < 21) {
  console.log("Good evening!");
} else {
  console.log("Good night!");
}
```

Output: `Good afternoon!`

The hour 14:

*   Is not < 12, skip first block
    
*   Is < 17, so run this block and print "Good afternoon!"
    

### **Step-by-Step Execution**

Let's trace through the grade example again:

```javascript
let marks = 65;

if (marks >= 80) {
  console.log("First Division");
} else if (marks >= 60) {
  console.log("Second Division");
} else if (marks >= 40) {
  console.log("Third Division");
} else {
  console.log("Fail");
}
```

Step 1: Variable `marks` is created with value 65

Step 2: Check condition 1: Is 65 >= 80? No, it is false

Step 3: Check condition 2: Is 65 >= 60? Yes, it is true

Step 4: Run the block for condition 2: Print "Second Division"

Step 5: Stop checking remaining conditions

Final Output:

```plaintext
Second Division
```

### **Important: Order Matters**

The order of conditions matters in an `else if` ladder. Let's see what happens if we change the order:

```javascript
let score = 85;

// Wrong order
if (score >= 60) {
  console.log("You passed");
} else if (score >= 80) {
  console.log("You got a great score");
}
```

Output: `You passed`

Even though the score is 85 (which is >= 80), we get "You passed" because the first condition (score >= 60) is already true, and JavaScript stops checking after that.

The correct order is from most specific to least specific:

```javascript
let score = 85;

// Correct order
if (score >= 90) {
  console.log("You got an excellent score");
} else if (score >= 80) {
  console.log("You got a great score");
} else if (score >= 60) {
  console.log("You passed");
} else {
  console.log("You failed");
}
```

Output: `You got a great score`

Now it works correctly because we check the most specific condition first.

* * *

## **5\. The switch Statement**

A `switch` statement is useful when you have many different options and you want to check if a value matches one of several fixed values. It is cleaner than writing many `else if` statements.

### **Syntax**

```javascript
switch (expression) {
  case value1:
    // Code runs if expression equals value1
    break;
  case value2:
    // Code runs if expression equals value2
    break;
  case value3:
    // Code runs if expression equals value3
    break;
  default:
    // Code runs if expression doesn't match any case
}
```

### **How It Works**

JavaScript evaluates the expression once. Then it compares the value with each case. When it finds a matching case, it runs the code for that case. The `break` keyword stops the switch statement. If no cases match, the `default` block runs (if provided).

### **Important: The break Statement**

The `break` statement is very important. It stops the switch from continuing to check other cases. If you forget `break`, JavaScript will run the code for the matching case AND all the cases after it until it finds a `break`. This is called "fall-through" and is usually not what you want.

### **Simple Examples**

#### **Example 1: Checking Days of the Week**

```javascript
let dayNumber = 3;

switch (dayNumber) {
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  case 3:
    console.log("Wednesday");
    break;
  case 4:
    console.log("Thursday");
    break;
  case 5:
    console.log("Friday");
    break;
  case 6:
    console.log("Saturday");
    break;
  case 7:
    console.log("Sunday");
    break;
  default:
    console.log("Invalid day number");
}
```

Output: `Wednesday`

The dayNumber is 3, so case 3 matches. We print "Wednesday" and then `break` stops the switch.

#### **Example 2: Student Grade to Message**

```javascript
let grade = "B";

switch (grade) {
  case "A":
    console.log("Excellent performance!");
    break;
  case "B":
    console.log("Good job!");
    break;
  case "C":
    console.log("Average performance");
    break;
  case "D":
    console.log("Poor performance");
    break;
  case "F":
    console.log("You failed the exam");
    break;
  default:
    console.log("Invalid grade");
}
```

Output: `Good job!`

#### **Example 3: Checking Traffic Light Color**

```javascript
let lightColor = "yellow";

switch (lightColor) {
  case "red":
    console.log("Stop!");
    break;
  case "yellow":
    console.log("Get ready!");
    break;
  case "green":
    console.log("Go!");
    break;
  default:
    console.log("Invalid color");
}
```

Output: `Get ready!`

### **What Happens Without break**

Let's see what happens if we forget the `break` statement:

```javascript
let dayNumber = 2;

switch (dayNumber) {
  case 1:
    console.log("Monday");
  case 2:
    console.log("Tuesday");
  case 3:
    console.log("Wednesday");
  case 4:
    console.log("Thursday");
  default:
    console.log("Invalid day");
}
```

Output:

```plaintext
Tuesday
Wednesday
Thursday
Invalid day
```

Without `break`, after finding case 2 and printing "Tuesday", the code continues to run case 3, case 4, and the default block. This is usually not what we want. Always remember to add `break` after each case.

### **Step-by-Step Execution**

Let's trace through a switch example:

```javascript
let fruit = "mango";

switch (fruit) {
  case "apple":
    console.log("Red fruit");
    break;
  case "mango":
    console.log("King of fruits");
    break;
  case "banana":
    console.log("Yellow fruit");
    break;
  default:
    console.log("Unknown fruit");
}
```

Step 1: Variable `fruit` is created with value "mango"

Step 2: Enter the switch statement with expression "mango"

Step 3: Check case "apple": Does "mango" === "apple"? No

Step 4: Check case "mango": Does "mango" === "mango"? Yes

Step 5: Run the code for case "mango": Print "King of fruits"

Step 6: Encounter `break`: Exit the switch

Step 7: Continue with the rest of the program

Final Output:

```plaintext
King of fruits
```

* * *

## **6\. When to Use switch vs if-else**

Both `switch` and `else if` can solve many of the same problems. How do you decide which one to use?

### **Use if-else When**

1.  You have conditions that involve ranges or comparisons
    
2.  Your conditions are complex
    
3.  You have only a few conditions to check
    

### **Use switch When**

1.  You are checking if a value matches one of several fixed values
    
2.  You have many different cases
    
3.  Your values are simple (strings, numbers)
    
4.  Your code looks cleaner with switch
    

* * *

## **Practical Examples with Explanation**

### **Example 1: Number Classification (Using if-else)**

Let's write a program that checks if a number is positive, negative, or zero:

```javascript
let number = 15;

if (number > 0) {
  console.log("The number is positive");
} else if (number < 0) {
  console.log("The number is negative");
} else {
  console.log("The number is zero");
}
```

Output: `The number is positive`

Why if-else? We are checking ranges and comparisons (greater than, less than), not fixed values.

Let's try with different numbers:

```javascript
let number = -5;

if (number > 0) {
  console.log("The number is positive");
} else if (number < 0) {
  console.log("The number is negative");
} else {
  console.log("The number is zero");
}
```

Output: `The number is negative`

```javascript
let number = 0;

if (number > 0) {
  console.log("The number is positive");
} else if (number < 0) {
  console.log("The number is negative");
} else {
  console.log("The number is zero");
}
```

Output: `The number is zero`

### **Example 2: Day of the Week (Using switch)**

Let's write a program that prints the day of the week based on a number:

```javascript
let dayNumber = 1;

switch (dayNumber) {
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  case 3:
    console.log("Wednesday");
    break;
  case 4:
    console.log("Thursday");
    break;
  case 5:
    console.log("Friday");
    break;
  case 6:
    console.log("Saturday");
    break;
  case 7:
    console.log("Sunday");
    break;
  default:
    console.log("Invalid day number");
}
```

Output: `Monday`

Why switch? We are checking if the number matches one of several fixed values (1, 2, 3, 4, 5, 6, or 7).

* * *

## **Visual Flowchart: if-else Decision Making**

Code

```plaintext
                 Start
                   |
                   v
            Check Condition 1
                 /    \
               True   False
               /        \
              v          v
         Run Block 1   Check Condition 2
              |           /    \
              |         True   False
              |         /        \
              |        v          v
              |   Run Block 2  Run Block 3
              |       |            |
              |       |            |
              +-------+----------->+
                      |
                      v
                     End
```

* * *

## **Visual Flowchart: switch-case Branching**

Code

```plaintext
                    Start
                      |
                      v
            Evaluate Expression
                      |
        ______________|______________
       |       |       |       |      |
       v       v       v       v      v
     Case   Case   Case   Case   Default
      1      2      3      4
      |       |       |       |      |
      v       v       v       v      v
    Block  Block  Block  Block   Block
      1      2      3      4       D
      |       |       |       |      |
      break   break   break   break
      |       |       |       |      |
      +-------+-------+-------+------+
              |
              v
             End
```

* * *

## **Summary**

1.  **Control flow** means making your code run different blocks based on conditions
    
2.  **if statement** runs code only if a condition is true
    
3.  **if-else statement** runs one block if true, another block if false
    
4.  **else if ladder** checks multiple conditions in order until one is true
    
5.  **switch statement** checks if a value matches one of several fixed values
    
6.  **break** is essential in switch statements to stop after a matching case
    
7.  **Use if-else** for ranges and complex conditions
    
8.  **Use switch** for checking fixed values
