Skip to main content

Command Palette

Search for a command to run...

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

Published
7 min read
Control Flow in JavaScript: If, Else, and Switch Explained

When you write code, you’re constantly making decisions:

  • If the user is logged in, show the dashboard.

  • If the score is above 90, show “A grade”.

  • If today is Sunday, send a summary email.

This “decision-making” is called control flow.

In this article, we’ll go through:

  • What does control flow mean?

  • if, if-else, else if ladder

  • switch statement

  • When to use switch vs if-else

  • Simple, practical examples and assignment ideas

What Is Control Flow?

Control flow is the order in which your code runs.

Normally, JavaScript runs your code top to bottom, one line at a time.

But with control flow statements, you can say:

  • “If this condition is true, run this block.”

  • “Otherwise, run something else.”

  • “Choose one of many options depending on a value.”

This is like real life:

  • If it’s raining → take an umbrella

  • Else if it’s cloudy → take a light jacket

  • Else → no extra gear needed

Programming gives you similar tools.

The if Statement

Use if when you want to run code only if a condition is true.

if (condition) {
  // code to run if condition is true
}

Example: check age

const age = 20;

if (age >= 18) {
  console.log("You are an adult.");
}
  • age >= 18 is the condition.

  • If it’s true, the code inside { ... } runs.

  • If it’s false, JavaScript skips that block.

The if-else Statement

Use if-else when you want two possible paths:

  • One if the condition is true

  • Another if it is false

Syntax

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

Example: pass or fail

const marks = 45;

if (marks >= 40) {
  console.log("You passed.");
} else {
  console.log("You failed.");
}
  • If marks is 40 or more → “You passed.”

  • Otherwise → “You failed.”

This is like:

  • If you have ₹100 or more → you can buy the item

  • Else → you cannot buy it


The else if Ladder

Sometimes you have more than two possibilities:

  • Grade A

  • Grade B

  • Grade C

  • Fail

The else if ladder lets you chain multiple conditions.

Syntax

if (condition1) {
  // runs if condition1 is true
} else if (condition2) {
  // runs if condition1 is false AND condition2 is true
} else if (condition3) {
  // runs if previous are false AND condition3 is true
} else {
  // runs if none of the above conditions are true
}

Example: grading system

const marks = 78;

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 D");
}

How it runs step by step:

  1. Check marks >= 90 → 78 >= 90? No → skip.

  2. Check marks >= 75 → 78 >= 75? Yes → print "Grade B".

  3. The rest of the ladder is not checked once one block matches.

This is like:

  • If marks ≥ 90 → A

  • Else if ≥ 75 → B

  • Else if ≥ 60 → C

  • Else → D

Only one block runs.

The switch Statement

switch is another way to handle multiple choices based on one value.

Instead of many if-else checks on the same variable, switch can be cleaner.

Syntax

switch (expression) {
  case value1:
    // code if expression === value1
    break;

  case value2:
    // code if expression === value2
    break;

  // more cases...

  default:
    // code if no case matches
}

Important: break in switch

  • break stops the switch from continuing to the next case.

  • Without break, JavaScript will “fall through” and run the next case’s code too, which is usually not what you want (at least when starting out).

Example: day of the week

const dayNumber = 3;
let dayName;

switch (dayNumber) {
  case 1:
    dayName = "Monday";
    break;
  case 2:
    dayName = "Tuesday";
    break;
  case 3:
    dayName = "Wednesday";
    break;
  case 4:
    dayName = "Thursday";
    break;
  case 5:
    dayName = "Friday";
    break;
  case 6:
    dayName = "Saturday";
    break;
  case 7:
    dayName = "Sunday";
    break;
  default:
    dayName = "Invalid day number";
}

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

Step by step:

  1. dayNumber is 3.

  2. switch compares it to each case:

    • 1? No.

    • 2? No.

    • 3? Yes → run that block.

  3. It sets dayName = "Wednesday";

  4. break; tells JavaScript: stop checking further cases.

If no case matches, the default block runs.

When to Use switch vs if-else

Both can do similar things, but they shine in different situations.

Use if / if-else / else if when:

  • You have range-based conditions:

    • marks >= 90

    • temperature < 0

    • age >= 18 && age < 60

  • Your conditions are more complex than “is it equal to this value?”

Example (ranges fit if-else better):

const temperature = 32;

if (temperature <= 0) {
  console.log("Freezing");
} else if (temperature <= 20) {
  console.log("Cold");
} else if (temperature <= 35) {
  console.log("Warm");
} else {
  console.log("Hot");
}

Use switch when:

  • You are checking one variable against many possible fixed values:

    • Day of week (1–7)

    • User role ("admin", "editor", "viewer")

    • Menu choice ("start", "help", "exit")

Example (cleaner with switch):

const role = "editor";

switch (role) {
  case "admin":
    console.log("Full access");
    break;
  case "editor":
    console.log("Edit access");
    break;
  case "viewer":
    console.log("Read-only access");
    break;
  default:
    console.log("Unknown role");
}

Rule of thumb:

  • Ranges / complex conditionsif-else.

  • One value with many discrete optionsswitch.


Assignment 1: Positive, Negative, or Zero

Task

Write a program that checks if a number is:

  • Positive

  • Negative

  • Zero

Example using if-else

const number = 0;

if (number > 0) {
  console.log("The number is positive.");
} else if (number < 0) {
  console.log("The number is negative.");
} else {
  console.log("The number is zero.");
}

Why use if-else?

  • You’re dealing with ranges and comparisons:

    • > 0

    • < 0

    • == 0

  • This fits if-else better than switch.


Assignment 2: Day of the Week Using switch

Task

Write a program that prints the day of the week given a number 1–7.

  • 1 → Monday

  • 2 → Tuesday

  • ...

  • 7 → Sunday

Example solution

const dayNumber = 5;
let dayName;

switch (dayNumber) {
  case 1:
    dayName = "Monday";
    break;
  case 2:
    dayName = "Tuesday";
    break;
  case 3:
    dayName = "Wednesday";
    break;
  case 4:
    dayName = "Thursday";
    break;
  case 5:
    dayName = "Friday";
    break;
  case 6:
    dayName = "Saturday";
    break;
  case 7:
    dayName = "Sunday";
    break;
  default:
    dayName = "Invalid day number";
}

console.log(dayName);

Why use switch here?

  • You’re checking one variable (dayNumber) against multiple exact values (1 to 7).

  • switch makes this pattern clean and easy to read.

1. If-Else Flowchart

Start →
     Check condition: number > 0?
      Yes → “Positive” → End
      No → Check number < 0?
      Yes → “Negative” → End
      No → “Zero” → End

This shows how only one path is followed based on conditions.

2. Switch-Case Branching Diagram

Start with dayNumber
  Arrow to a box: switch(dayNumber)
   Branches:
   1 → “Monday”
   2 → “Tuesday”
   ...
   7 → “Sunday”
   default → “Invalid day”

Each branch ends after a break, showing that only the matching case runs.

Summary

  • Control flow controls how your program decides what to run next.

  • Use:

    • if for simple “run this only if true”.

    • if-else When there are exactly two paths.

    • else if ladder when there are multiple ordered conditions (often ranges).

    • switch When checking one value against many fixed options.

  • break in switch stops execution from falling through into the next case.

  • Choose your control structure based on:

    • Type of conditions (ranges vs fixed values).

    • Readability and clarity of your code.

Happy Coding!