Skip to main content

Command Palette

Search for a command to run...

Control Flow in JavaScript: if, else, and switch Explained

Published
6 min read
Control Flow in JavaScript: if, else, and switch Explained
S
Full-stack developer obsessed with performance, scalability, and clean systems. I use Arch btw.

Every program makes decisions. Should this user see the dashboard or the login page? Did the student pass or fail? Is this item in stock? Code that just runs top to bottom, line by line, without reacting to anything is not very useful. Control flow is what lets your program look at a situation and do something appropriate.

In JavaScript, control flow mostly comes down to a handful of constructs: if, if-else, else if, and switch. They're not complicated, but the small differences between them matter more than most beginners expect.


What "Control Flow" Actually Means

When JavaScript runs your code, it starts at the top and works its way down. Control flow is anything that changes that path. A condition is evaluated, and depending on the result, the program either enters a block of code or skips it.

Think of it like a security checkpoint. The guard checks your ID. If you're old enough, you get in. If not, you don't. The program doesn't do both things. It picks one path and follows it.

That's it. Everything else is just syntax.


The if Statement

The if statement is the simplest form of control flow. It runs a block of code only when a condition is true. If the condition is false, the block is skipped entirely.

let age = 20;

if (age >= 18) {
  console.log("You can vote.");
}

Here, JavaScript checks whether age >= 18 is true. It is (20 is greater than 18), so it prints the message.

Change age to 15 and nothing prints. The condition fails, the block is skipped, and execution continues after the closing brace.

One thing worth noting: the condition inside if() gets converted to a boolean. Values like 0, "", null, undefined, NaN, and false are all falsy in JavaScript. Everything else is truthy. This matters when you're checking variables that might be empty or unset.


The if-else Statement

Sometimes you want something to happen either way. If the condition is true, do this. If it's false, do that instead. That's if-else.

let marks = 45;

if (marks >= 50) {
  console.log("Pass");
} else {
  console.log("Fail");
}

Only one of those two blocks will ever run. JavaScript evaluates the condition, takes the true branch or the false branch, and moves on.

This is cleaner than writing two separate if statements that check opposite conditions. It also signals intent: these two outcomes are mutually exclusive.


The else if Ladder

Real situations often have more than two outcomes. A student doesn't just pass or fail. They might get an A, B, C, or fail. That's where else if comes in.

let marks = 72;

if (marks >= 90) {
  console.log("Grade: A");
} else if (marks >= 75) {
  console.log("Grade: B");
} else if (marks >= 60) {
  console.log("Grade: C");
} else {
  console.log("Grade: F");
}

JavaScript checks each condition from top to bottom. The moment one is true, it runs that block and skips everything below it. So if marks is 72, the first two conditions fail and the third one passes. It prints Grade: C and stops.

This order matters. If you accidentally put a broader condition above a narrower one, the narrower one may never get a chance to run. For example, if you put marks >= 60 before marks >= 75, any mark above 60 would always match the first condition and never reach the second.

The final else at the bottom acts as a catch-all. It runs when none of the conditions above are true. You don't have to include it, but it's good practice when you want to handle unexpected cases.


The switch Statement

The switch statement is a different approach to branching. Instead of writing a chain of conditions, you give it a single value and match it against specific cases.

let day = "Monday";

switch (day) {
  case "Saturday":
  case "Sunday":
    console.log("Weekend");
    break;
  case "Monday":
    console.log("Start of the work week");
    break;
  case "Friday":
    console.log("Almost there");
    break;
  default:
    console.log("Midweek");
}

JavaScript evaluates day, finds the matching case, runs the code there, and stops at break.

What break does

Without break, JavaScript keeps executing the code in the next case, even if that case's value doesn't match. This is called "fall-through" and it causes bugs that are surprisingly hard to spot.

let color = "red";

switch (color) {
  case "red":
    console.log("Red");
  case "blue":
    console.log("Blue");   // This also runs if break is missing above
  default:
    console.log("Other");  // And this
}

Without break after "red", all three lines print. With it, only "Red" prints. Always include break unless you intentionally want fall-through (which is rare, and usually worth a comment when you do it).

The default case is like else. It runs when nothing matches.


When to Use switch vs if-else

This comes up a lot and the honest answer is: it depends on what you're comparing.

Use if-else when:

  • You're checking ranges or inequalities (age >= 18, score < 50)

  • Your conditions involve different variables or complex expressions

  • You only have two or three branches

Use switch when:

  • You're comparing one variable against several fixed values

  • You have many possible cases and readability is getting messy with else if

  • The values are strings or numbers with discrete, known options

Compare these two versions of the same logic:

// if-else
if (status === "active") {
  activate();
} else if (status === "inactive") {
  deactivate();
} else if (status === "pending") {
  showPending();
} else {
  showError();
}
// switch
switch (status) {
  case "active":
    activate();
    break;
  case "inactive":
    deactivate();
    break;
  case "pending":
    showPending();
    break;
  default:
    showError();
}

The switch version is easier to scan. You can see all the possible values at a glance. The if-else version looks fine here but starts to get crowded with six or seven branches.

That said, if-else is more flexible. You can't use ranges in a switch case. case marks >= 90 is not valid syntax. For anything involving comparisons, stick with if-else.


A Practical Example

Here's a small program that uses both, so you can see them side by side in realistic code:

let age = 17;
let memberType = "student";

if (age < 18) {
  console.log("Minor: parental consent required");
} else {
  console.log("Adult: no restrictions");
}

switch (memberType) {
  case "student":
    console.log("50% discount applied");
    break;
  case "senior":
    console.log("30% discount applied");
    break;
  case "regular":
    console.log("No discount");
    break;
  default:
    console.log("Unknown member type");
}

The if-else handles the age check because it's a range comparison. The switch handles the member type because it's matching one variable against known string values.


Conclusion

Control flow is not a difficult topic, but getting comfortable with it takes some practice. The syntax becomes second nature quickly. What takes longer is developing the instinct for which construct fits the situation. Once you stop thinking about syntax and start thinking about what the program needs to decide, it gets easier.