Skip to main content

Command Palette

Search for a command to run...

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

Updated
4 min read
Control Flow in JavaScript: If, Else, and Switch Explained

Have you ever wondered how an app "knows" to let you log in only if your password is correct? Or how a game knows it’s "Game Over" when your health reaches zero?

This isn't magic—it’s Control Flow.

What is Control Flow?

In programming, Control Flow is the order in which individual statements or instructions are executed.

Imagine you are driving. If the road is a straight line with no turns, you just keep going. But real roads have intersections, traffic lights, and detours. Control flow structures are the "traffic signals" of code. They allow the program to skip sections, choose between paths, or repeat actions based on specific conditions.

1. The if Statement: The Basic Gate

The if statement is the simplest form of control flow. It only cares about one thing: Is the condition true?

let userLoggedIn = true;

if (userLoggedIn) {
    console.log("Welcome back, User! ✨");
}

How it runs step-by-step:

  1. Evaluation: The engine looks inside the parentheses ().

  2. Conversion: It checks if the value is "truthy."

  3. Execution: If true, it runs the code inside the curly braces {}. If false, it simply skips to the next line of code after the block.

2. The if-else Statement: The Fork in the Road

Most decisions have an alternative. The else block acts as a safety net for when your if condition fails.

let temperature = 15;

if (temperature > 20) {
    console.log("It's a warm day! ☀️");
} else {
    console.log("Grab a jacket. 🧥");
}

Pro-Tip: Avoid "Nested Complexity." Beginners often put if statements inside other if statements. This is called "Pyramid of Doom" code. If you find yourself nesting too deep, it's time to use an else if ladder or a switch.

3. The else if Ladder: Multi-Condition Logic

When you have more than two distinct paths, you "chain" your conditions. JavaScript will check them in order and stop as soon as it finds one that works.

let marks = 85;

if (marks >= 90) {
    console.log("Grade: A+");
} else if (marks >= 80) {
    console.log("Grade: A");
} else if (marks >= 70) {
    console.log("Grade: B");
} else {
    console.log("Keep studying! 📚");
}

Crucial Note: The order matters! If you checked for marks >= 70 first, a student with 95 would get a "B" because that condition would be met first, and the rest of the ladder would be ignored.

4. The switch Statement: The Efficiency Expert

The switch statement is an alternative to the else if ladder. It’s best used when you are checking a single variable against a list of specific, constant values.

let fruit = "Apple";

switch (fruit) {
    case "Banana":
        console.log("Yellow and sweet!");
        break;
    case "Apple":
        console.log("Crunchy and red!");
        break;
    case "Orange":
        console.log("Juicy and citrusy!");
        break;
    default:
        console.log("Unknown fruit.");
}

Why the break keyword is mandatory:

In JavaScript, switch uses "fall-through" logic. If you match "Apple" but forget the break, the computer will keep executing the code for "Orange" and the "default" case too! The break tells the engine: "I'm done here, exit the switch block."

switch vs. if-else: Which one to pick?

Feature

if-else

switch

Comparisons

Can use <, >, &&, `

cannot use <, >, &&, `

Readability

Better for range-based logic

Better for long lists of discrete values

Performance

Slightly slower for many conditions

Slightly faster for many conditions

Assignment: Put it into Practice

Try writing these two programs in your browser console:

  1. Number Sign Checker: * Create a variable num.

    • Use an if-else if-else structure to log whether the number is "Positive", "Negative", or "Zero".
  2. Day of the Week: * Create a variable dayNumber (1-7).

    • Use a switch statement to print the name of the day (e.g., 1 = "Monday").

    • Bonus: Add a default case to handle numbers that aren't 1-7.

Summary

Control flow is the "brain" of your JavaScript logic. By mastering if, else, and switch, you move from writing simple scripts to building intelligent, responsive applications.

JS Under the Hood: The Engine Room

Part 5 of 24

Ever wondered why your code actually runs? We’re going beyond the syntax to explore the V8 engine, memory management, and the "magic" that happens between your keyboard and the screen. Just deep dives.

Up next

Function Declaration vs Function Expression: What’s the Difference?

If you’ve been following along with the JS Under The Hood series, you know we’ve spent a lot of time talking about how JavaScript handles variables and memory. But let's be honest: variables alone are