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
S
Software Engineer specializing in backend development and API architecture with 6+ years of experience. I build scalable web applications using PHP, REST/GraphQL APIs, and modern JavaScript, with strong expertise in WordPress, headless CMS solutions, and system integrations. Passionate about creating secure, high-performance systems that translate complex business needs into efficient technical solutions.

Every app you've ever used makes decisions. Show this page or that one. Allow access or block it. Display a discount or full price. That decision-making ability in code is called control flow β€” and it's one of the most important concepts in programming.

Let's break it down from scratch.


What is Control Flow?

By default, JavaScript reads your code top to bottom, one line at a time. Control flow lets you change that path based on conditions.

Think of it like a road with forks:

You're driving. You see a sign: "If it's raining β†’ take the bridge. Otherwise β†’ take the highway."

Your code does the exact same thing β€” it checks a condition, then takes the right path.


1. The if Statement

The simplest decision: do something only if a condition is true.

let age = 20;

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

If the condition inside ( ) is true, the code inside { } runs. If it's false, JavaScript skips it completely.

let age = 15;

if (age >= 18) {
  console.log("You can vote."); // ❌ skipped β€” condition is false
}

2. The if-else Statement

What if you want to do something either way β€” one thing if true, another if false?

let age = 15;

if (age >= 18) {
  console.log("You can vote.");
} else {
  console.log("You are too young to vote.");
}
// Output: You are too young to vote.

Only one block runs β€” either if or else. Never both.

Real example β€” checking if a user is logged in:

let isLoggedIn = false;

if (isLoggedIn) {
  console.log("Welcome back!");
} else {
  console.log("Please log in first.");
}
// Output: Please log in first.

3. The else if Ladder

What if you have more than two possible outcomes? Use else if to check multiple conditions one by one.

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");
}
// Output: Grade: C

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

marks = 72
  ↓
Is 72 >= 90? ❌ No β†’ move down
Is 72 >= 75? ❌ No β†’ move down
Is 72 >= 60? βœ… Yes β†’ print "Grade: C" β†’ stop

The final else is your safety net β€” it runs when none of the conditions above matched.


4. The switch Statement

When you're checking one variable against many specific values, switch is cleaner than a long else if chain.

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;
  default:
    console.log("Weekend");
}
// Output: Wednesday

How switch works step by step:

day = 3
  ↓
Does day === 1? ❌ No
Does day === 2? ❌ No
Does day === 3? βœ… Yes β†’ print "Wednesday" β†’ break β†’ exit

What does break do?

break tells JavaScript: "Stop here. Don't check any more cases."

Without break, JavaScript keeps running into the next cases even after finding a match β€” this is called fall-through:

let day = 3;

switch (day) {
  case 3:
    console.log("Wednesday"); // βœ… runs
  case 4:
    console.log("Thursday");  // ⚠️ also runs! (no break above)
  case 5:
    console.log("Friday");    // ⚠️ also runs!
    break;
}
// Output: Wednesday, Thursday, Friday  ← probably not what you wanted

Always add break at the end of each case unless you intentionally want fall-through.

The default case

default is like else β€” it runs when no case matched:

let day = 9;

switch (day) {
  case 1:
    console.log("Monday");
    break;
  default:
    console.log("Invalid day"); // runs because no case matched
}
// Output: Invalid day

5. switch vs if-else β€” When to Use Which?

Situation Use
Checking a range (>, <, >=) if-else
Checking multiple specific values switch
Complex conditions (&&, `
One variable, many exact matches switch
2-3 conditions only if-else

Use if-else for:

// ranges and complex conditions
if (temperature > 35) {
  console.log("Too hot");
} else if (temperature > 20) {
  console.log("Pleasant");
} else {
  console.log("Cold");
}

Use switch for:

// one value, many fixed options
switch (userRole) {
  case "admin":
    console.log("Full access");
    break;
  case "editor":
    console.log("Can edit posts");
    break;
  case "viewer":
    console.log("Read only");
    break;
  default:
    console.log("No access");
}

Putting It All Together

let score = 55;

// if-else ladder
if (score >= 90) {
  console.log("Excellent!");
} else if (score >= 75) {
  console.log("Good job!");
} else if (score >= 50) {
  console.log("You passed.");
} else {
  console.log("Better luck next time.");
}
// Output: You passed.

// same score check with a grade letter using switch
let grade = score >= 90 ? "A" : score >= 75 ? "B" : score >= 50 ? "C" : "F";

switch (grade) {
  case "A":
    console.log("Distinction");
    break;
  case "B":
    console.log("First Class");
    break;
  case "C":
    console.log("Pass");
    break;
  default:
    console.log("Fail");
}
// Output: Pass

πŸ§ͺ Your Turn β€” Assignment Challenge

1. Check if a number is positive, negative, or zero

let num = -7;

if (num > 0) {
  console.log("Positive");
} else if (num < 0) {
  console.log("Negative");
} else {
  console.log("Zero");
}
// Try with: 0, 42, -3

2. Print the day of the week using switch

let day = 5;

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: Friday

3. Which did you use and why?

  • Used if-else for the number check because we're comparing ranges (> 0, < 0) β€” switch can't handle that.

  • Used switch for the day check because we're matching one variable against exact fixed values β€” cleaner than 7 else if blocks.


Wrapping Up

Control flow is how your program thinks. Without it, every user would see the same page, every input would get the same response, every action would produce the same result. That's not an app β€” that's a static page.

Master if, else if, and switch and you've unlocked the decision-making brain of JavaScript.

8 views

More from this blog

U

Understanding JavaScript

17 posts