Skip to main content

Command Palette

Search for a command to run...

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

Published
β€’8 min read
Control Flow in JavaScript: If, Else, and Switch Explained

By Saurabh Prajapati β€” Full-Stack Engineer @ IBM India | GenAI & React Enthusiast


Wait β€” What Even Is "Control Flow"?

Let me be honest. When I first saw the term "control flow" in a programming book, I thought it sounded way more complicated than it actually is.

Here's the simple truth: control flow just means the order in which your code runs.

By default, JavaScript reads your code from top to bottom, line by line. But what if you only want certain code to run in certain situations? That's exactly where control flow comes in.

Think about real life for a second:

🚦 If the traffic light is green β†’ you drive. Otherwise β†’ you stop.

That's control flow. You're making a decision based on a condition.

In JavaScript, we do the same thing. We check a condition, and based on whether it's true or false, we run different pieces of code.

Let's explore exactly how that works.


1. The if Statement

The if statement is the most basic building block of decision-making in JavaScript.

Syntax

if (condition) {
  // code runs only if condition is true
}

Real Example

let age = 20;

if (age >= 18) {
  console.log("You are eligible to vote!");
}

Output: You are eligible to vote!

The code inside the curly braces {} only runs if the condition age >= 18 is true.

If age was 15, nothing would happen at all. The block would be completely skipped.

πŸ’‘ I wish I knew this earlier: The condition inside if() doesn't have to be a comparison. Anything "truthy" works β€” like a non-empty string, a number that isn't zero, or even an object. JavaScript is flexible like that.


2. The if-else Statement

Okay, but what if you want something to happen even when the condition is false? That's where else comes in.

Syntax

if (condition) {
  // runs if condition is true
} else {
  // runs if condition is false
}

Real Example

let marks = 35;

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

Output: You failed. Better luck next time.

Think of if-else like a fork in the road. You always take one path or the other β€” never both, never neither.

[Condition?]
    |
   YES β†’ run if block
    |
   NO  β†’ run else block

This is the most common pattern you'll use as a developer. I use it literally every day at work.


3. The else if Ladder

Sometimes two options aren't enough. What if you have three or more conditions to check?

That's where else if steps in.

Syntax

if (condition1) {
  // runs if condition1 is true
} else if (condition2) {
  // runs if condition2 is true
} else {
  // runs if none of the above are true
}

Real Example β€” Grading System

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 if (marks >= 40) {
  console.log("Grade: D");
} else {
  console.log("Grade: F β€” Please retry");
}

Output: Grade: C

JavaScript checks each condition from top to bottom. The moment it finds one that's true, it runs that block and stops checking the rest.

This is important! Here's what I mean:

let marks = 95;

if (marks >= 60) {
  console.log("Grade: C"); // ← This runs first... and stops!
} else if (marks >= 90) {
  console.log("Grade: A"); // ← This never runs!
}

See the bug? Order matters. Always put your most specific or highest condition first.

πŸ˜… I made this exact mistake when I was learning. Spent 20 minutes debugging a grading script before realizing the conditions were in the wrong order. Lesson learned.


πŸ—ΊοΈ Flowchart: How if-else Works

        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
        β”‚  Start          β”‚
        β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                 β”‚
        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”
        β”‚  Check          β”‚
        β”‚  Condition 1?   β”‚
        β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           YES   β”‚    NO
     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    └───────────┐
     β–Ό                            β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Run     β”‚              β”‚ Check          β”‚
β”‚ Block 1 β”‚              β”‚ Condition 2?   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜              β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜
                            YES   β”‚    NO
                      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    └──────────┐
                      β–Ό                            β–Ό
                 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”               β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                 β”‚ Run     β”‚               β”‚ Run else    β”‚
                 β”‚ Block 2 β”‚               β”‚ block       β”‚
                 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜               β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

4. The switch Statement

Now here's something I found really interesting when I first discovered it.

Imagine you're building a day-of-the-week app. With if-else, it would look like this:

if (day === 1) {
  console.log("Monday");
} else if (day === 2) {
  console.log("Tuesday");
} else if (day === 3) {
  console.log("Wednesday");
// ...and so on

That's a lot of repetition. switch is designed exactly for situations like this β€” when you're comparing one variable against many fixed values.

Syntax

switch (expression) {
  case value1:
    // code
    break;
  case value2:
    // code
    break;
  default:
    // code if no case matches
}

Real Example β€” Day of the Week

let day = 3;

switch (day) {
  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:
    console.log("Saturday");
    break;
  case 7:
    console.log("Sunday");
    break;
  default:
    console.log("Invalid day number");
}

Output: Wednesday

Wait, What's break Doing Here?

Great question. I was confused about this too at first.

Without break, JavaScript doesn't stop after finding a matching case. It keeps running every case below it β€” which is almost never what you want.

This behavior is called "fall-through".

let day = 3;

switch (day) {
  case 3:
    console.log("Wednesday"); // ← This runs
  case 4:
    console.log("Thursday");  // ← This ALSO runs (no break!)
  case 5:
    console.log("Friday");    // ← And this too!
}

Output:

Wednesday
Thursday
Friday

See the problem? We matched case 3, but without break, it kept going.

Always add break at the end of each case. (Unless you intentionally want fall-through β€” which is rare, but possible for grouping cases.)

Grouping Cases (Intentional Fall-Through)

let day = 6;

switch (day) {
  case 6:
  case 7:
    console.log("It's the weekend! πŸŽ‰");
    break;
  default:
    console.log("It's a weekday.");
}

Output: It's the weekend! πŸŽ‰

Here both case 6 and case 7 fall through to the same code block. This is a clean pattern for grouping similar cases.

What About default?

default is like the else in a switch. It runs when no case matches.

let color = "purple";

switch (color) {
  case "red":
    console.log("Red");
    break;
  case "blue":
    console.log("Blue");
    break;
  default:
    console.log("Unknown color"); // ← This runs
}

πŸ—ΊοΈ Switch Branching Diagram

         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
         β”‚  switch(value)   β”‚
         β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                  β”‚
       β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
       β–Ό          β–Ό          β–Ό
  [case 1]    [case 2]   [default]
       β”‚          β”‚          β”‚
    (code)     (code)     (code)
       β”‚          β”‚          β”‚
    [break]    [break]    (end)

5. When to Use switch vs if-else?

This is the question I kept asking myself. Here's what I've figured out after using both in real projects:

Situation Use This
Checking a range (e.g., marks > 80) if-else
Comparing one value to many fixed options switch
Complex conditions with && or `
Menu selection, day/month names, status codes switch
Two or three simple options if-else
Five or more fixed values switch

A Quick Rule of Thumb

Use if-else when you need flexible conditions. Use switch when you're matching one thing to many exact values.


Key Discoveries Along the Way

Here's what genuinely surprised me while diving into this topic:

1. switch uses strict equality (===) It doesn't do type conversion. So case "1" won't match if your value is the number 1.

let input = 1; // number

switch (input) {
  case "1":  // ← string "1" β€” won't match!
    console.log("One");
    break;
  case 1:    // ← number 1 β€” matches!
    console.log("One (number)");
    break;
}

2. You can use switch with strings too

let language = "JavaScript";

switch (language) {
  case "JavaScript":
    console.log("Runs in the browser!");
    break;
  case "Python":
    console.log("Great for data science!");
    break;
  default:
    console.log("Cool choice!");
}

3. if conditions can be anything truthy

let name = "Saurabh";

if (name) {
  console.log("Name exists: " + name);
}
// Works! Because a non-empty string is truthy.

Wrapping Up

Control flow is one of those foundational concepts that everything else in programming is built on. Once you understand how if, else, and switch work, you start seeing them everywhere.

Here's a quick recap of what we covered:

  • if β€” runs code when a condition is true

  • if-else β€” runs one block if true, another if false

  • else if β€” chains multiple conditions together

  • switch β€” cleanly matches one value against many fixed options

  • break β€” essential in switch to prevent fall-through

  • default β€” the fallback when no case matches

About the Author

Saurabh Prajapati (SP) Full-Stack Software Engineer at IBM India Software Lab, working on cloud-native enterprise solutions with Maximo. Passionate about GenAI, React, and modern web technologies.

Skills: JavaScript Β· TypeScript Β· React Β· Next.js Β· Node.js Β· LangChain Β· OpenAI API Β· AWS Β· Docker

πŸ“§ saurabhprajapati120@gmail.com πŸ™ GitHub: prajapatisaurabh πŸ’Ό LinkedIn: saurabh-prajapati

More from this blog