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

In the real world, we make decisions constantly:

*   **If** it is raining, **then** take an umbrella.
    
*   **Else**, leave it at home.
    

In programming, this is called **Control Flow**. By default, code runs in a straight line from top to bottom. Control flow allows us to create "forks in the road," where the computer chooses which path to take based on the conditions we set.

* * *

## The `if` Statement (The Basic Choice)

The `if` statement is the simplest form of control. If a condition is true, the code inside the curly braces runs. If it's false, the computer simply skips it.

```plaintext
let marks = 45;

if (marks >= 33) {
  console.log("You passed!");
}
```

* * *

### **The** `if-else` **Statement (The Fork in the Road)**

What if you want something else to happen when the condition is false? That’s where `else` comes in.

![](https://cdn.hashnode.com/uploads/covers/6815b28437922044be2f12c2/100c91cb-1f90-4086-ba26-c795758f989c.png align="center")

```plaintext
let age = 16;

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

* * *

### **The** `else if` **Ladder (Multiple Options)**

Life isn't always "Yes" or "No." Sometimes there are several possibilities. The `else if` ladder lets you check multiple conditions in order. The computer stops at the **first** true condition it finds.

```plaintext
let time = 14; // 2:00 PM

if (time < 12) {
  console.log("Good Morning");
} else if (time < 17) {
  console.log("Good Afternoon");
} else {
  console.log("Good Evening");
}
```

* * *

## The `switch` Statement (The Organized List)

When you have one variable and you want to check it against many specific values (like days of the week or menu items), an `else if` ladder can get messy. The `switch` statement is a cleaner way to handle this.

Why do we need `break`?

Think of `break` as your exit strategy. Without it, the code will "fall through" and execute every single case below the one that matched, even if they aren't true!

```plaintext
let fruit = "Apple";

switch (fruit) {
  case "Banana":
    console.log("Yellow and curved.");
    break;
  case "Apple":
    console.log("Red and crunchy.");
    break;
  default:
    console.log("Unknown fruit.");
}
```

* * *

## When to use `switch` vs `if-else`?

![](https://cdn.hashnode.com/uploads/covers/6815b28437922044be2f12c2/5436db19-155d-4264-a106-e2bbca524d93.png align="center")

* * *

## Conclusion

Control flow is the brain of your application. By mastering `if-else` and `switch`, you’ve moved from just writing "scripts" to building "logic." Whether you're validating a login form or determining the path of a player in a game, these structures are the foundation of every decision your program will ever make.
