Skip to main content

Command Palette

Search for a command to run...

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

Updated
•6 min read•View as Markdown
R

I am a developer from India.

Introduction: What is Control Flow?

Imagine you are driving a car. You don't just drive straight forever; you make decisions based on what you see:

  • If the light is red, then stop.

  • Else if the light is yellow, then slow down.

  • Else (if green), then go.

In programming, this decision-making process is called Control Flow. By default, JavaScript runs code line-by-line from top to bottom. Control flow statements allow us to break that linear sequence, skip certain lines, or repeat actions based on specific conditions. It turns a static script into a dynamic, intelligent program.


The if Statement: The Basic Gatekeeper

The if statement is the simplest form of control flow. It executes a block of code only if a specific condition is true.

Syntax

if (condition) {
  // Code runs ONLY if condition is true
}

Real-Life Analogy

"If it is raining, take an umbrella." If it's not raining, you do nothing regarding the umbrella.

Example: Checking Age

let age = 20;

if (age >= 18) {
  console.log("You are eligible to vote.");
}
// If age was 15, nothing would happen here.

How it runs step-by-step:

  1. JavaScript checks age >= 18.

  2. Since 20 >= 18 is true, it enters the curly braces {}.

  3. It prints the message.

  4. It continues to the next line of code outside the if block.


The if-else Statement: Two Paths

Sometimes you need to handle both scenarios: when the condition is true and when it is false. That's where else comes in.

Syntax

if (condition) {
  // Runs if true
} else {
  // Runs if false
}

Real-Life Analogy

"If you have a ticket, enter the cinema. Otherwise, go buy one."

Example: Pass or Fail

let marks = 45;
let passingMark = 50;

if (marks >= passingMark) {
  console.log("Congratulations! You passed.");
} else {
  console.log("Sorry, you need to study more.");
}
// Output: "Sorry, you need to study more."

The else if Ladder: Multiple Choices

What if there are more than two possibilities? You can chain multiple conditions using else if.

Syntax

if (condition1) {
  // Runs if condition1 is true
} else if (condition2) {
  // Runs if condition1 is false BUT condition2 is true
} else if (condition3) {
  // Runs if previous are false BUT condition3 is true
} else {
  // Runs if ALL conditions above are false
}

Important Rule: First Match Wins

JavaScript evaluates conditions from top to bottom. As soon as it finds a true condition, it executes that block and skips the rest of the ladder.

Example: Grading System

let score = 85;

if (score >= 90) {
  console.log("Grade: A");
} else if (score >= 80) {
  console.log("Grade: B"); // This runs because 85 >= 80
} else if (score >= 70) {
  console.log("Grade: C"); // Skipped entirely
} else {
  console.log("Grade: F"); // Skipped entirely
}

The switch Statement: The Multi-Way Branch

When you need to check one variable against many specific values (exact matches), a long if-else if ladder can become messy. The switch statement is cleaner for this scenario.

Syntax

switch (expression) {
  case value1:
    // Code if expression === value1
    break;
  case value2:
    // Code if expression === value2
    break;
  default:
    // Code if no cases match
}

Key Concept: The break Keyword

This is the most critical part of switch.

  • With break: The code stops after executing the matching case.

  • Without break: JavaScript "falls through" to the next case, executing its code too, even if it doesn't match! This is usually a bug, but sometimes used intentionally.

Example: Days of the Week

let day = 3;
let dayName;

switch (day) {
  case 1:
    dayName = "Monday";
    break; // Stops here if day is 1
  case 2:
    dayName = "Tuesday";
    break;
  case 3:
    dayName = "Wednesday";
    break; // Matches here, sets value, then breaks
  case 4:
    dayName = "Thursday";
    break;
  default:
    dayName = "Invalid Day";
}

console.log(dayName); // Output: "Wednesday"

When to Use if-else vs. switch

Feature if-else Ladder switch Statement
Condition Type Can check ranges (>, <), complex logic
Readability Can get messy with many conditions. Very clean and readable for many specific options.
Performance Slightly slower for very large lists (evaluates every condition until true). Often optimized by engines for large lists of cases.
Best Use Case "Is age > 18?", "Is user logged in AND admin?", "Is price < 100?" Menu selections, Status codes (200, 404, 500), Days of week, Specific string matches.

Rule of Thumb:

  • Use if for ranges and complex logic.

  • Use switch for specific, discrete values.


Interactive Assignment

Here are two practical exercises to solidify your understanding.

Exercise 1: Positive, Negative, or Zero

Goal: Use an if-else if ladder to categorize a number.

let number = -15;

if (number > 0) {
  console.log(`${number} is positive.`);
} else if (number < 0) {
  console.log(`${number} is negative.`);
} else {
  console.log("The number is zero.");
}
// Try changing 'number' to 0, 10, and -5 to see different outputs.

Why use if-else here? Because we are checking mathematical ranges (> 0, < 0), which switch cannot do easily.

Exercise 2: Day of the Week Printer

Goal: Use a switch statement to map numbers to days.

let dayCode = 5;

switch (dayCode) {
  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:
  case 7: // Intentional fallthrough: Both 6 and 7 represent Weekend
    console.log("Weekend!");
    break;
  default:
    console.log("Invalid day code");
}

Why use switch here? We are matching one variable (dayCode) against exact integers. It is much cleaner than writing if (dayCode == 1) ... else if (dayCode == 2)....


Common Pitfalls to Avoid

  1. Forgetting break in Switch: This causes "fallthrough," where multiple cases run unintentionally.

  2. Using = instead of == or === in If:

    • if (x = 5) assigns 5 to x and always evaluates to true.

    • if (x === 5) checks if x is equal to 5. Always use ===.

  3. Complex Nested Ifs: Avoid putting if statements inside if statements inside if statements (3+ levels deep). It makes code hard to read. Consider returning early or using logical operators (&&) instead.


Conclusion

Control flow is the brain of your JavaScript program. It allows your code to react to user input, data changes, and real-world scenarios. Mastering if, else, and switch gives you the power to write logic that feels alive. Remember: use if for flexibility and ranges, and switch for clean, specific value matching. Always double-check your break statements!