Skip to main content

Command Palette

Search for a command to run...

Control Flow in JavaScript: If, Else, and Switch

Updated
3 min read

1. The if Statement

The if statement is the simplest way to make a decision in code. It basically says, "Check if this condition is true. If it is, run the code inside the block."

let age = 20;

if (age >= 18) {
  console.log("Welcome in!");
}
  1. It sees the variable age is set to 20.

  2. It looks at the condition (age >= 18).

  3. Because 20 is indeed greater than 18, the condition is "true".

  4. Since it's true, it goes inside the curly braces {} and prints "Welcome in!".

2. The if-else Statement

The if statement is great, but what if the condition is false and you still want something to happen? That’s where else comes in. It acts as a backup plan.

let marks = 35;

if (marks >= 40) {
  console.log("You passed!");
} else {
  console.log("You failed. Better luck next time.");
}

How this runs:

  1. The marks variable is 35.

  2. The computer checks (marks >= 40).

  3. Because it's false, it skips the first block of code completely.

  4. It sees the else block and automatically runs it, printing "You failed. Better luck next time."

3. The else if

Sometimes a simple "yes or no" isn't enough. You might have multiple conditions to check. You can string these together using else if.

let score = 85;

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

4. The switch Statement

If you have a lot of specific values to check, writing a massive else if ladder gets really messy and hard to read.

let trafficLight = "yellow";

switch (trafficLight) {
  case "green":
    console.log("Go!");
    break;
  case "yellow":
    console.log("Slow down!");
    break;
  case "red":
    console.log("Stop!");
    break;
  default:
    console.log("Invalid light color.");
}

Why do we need break?

I feel this is the biggest trap for beginners. If the computer finds a match, it will run that code. But if you don't include the word break, the code will "fall through" and automatically run the "red" and "default" console logs too, even though they don't match!

When to use which?

  • Use if-else when - You are checking for ranges (like age > 18) or comparing different variables. It's your most flexible, everyday tool.

  • Use switch when - You have one specific variable and you are checking it against a bunch of exact, fixed values. It keeps your code much easier to read.