Skip to main content

Command Palette

Search for a command to run...

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

Updated
17 min read
Control Flow in JavaScript: if, else, and switch Explained

Who is this for? If you are just starting with JavaScript and want to understand how your program makes decisions — checking conditions and choosing what to do — this guide walks you through everything from scratch.


Table of Contents

  1. What Is Control Flow?

  2. The if Statement

  3. The if-else Statement

  4. The else if Ladder

  5. The switch Statement

  6. When to Use switch vs if-else

  7. Diagrams

  8. Practice Assignment


Introduction

Every program makes decisions. Should the user be allowed to log in? Is this score high enough to pass? What day of the week is it?

In real life, you make hundreds of decisions every day without thinking — "If it is raining, I will take an umbrella. Otherwise, I will leave it at home." Control flow in programming is exactly the same idea: if this condition is true, do this — otherwise, do something else.

JavaScript gives you clean, simple tools to express these decisions in code. Let us go through them one by one.

💡 Open your browser console (F12 → Console tab) and try every example as you read.


1. What Is Control Flow?

By default, JavaScript executes your code line by line, top to bottom:

console.log("Line 1");
console.log("Line 2");
console.log("Line 3");
// Output: Line 1 → Line 2 → Line 3 (always, in that order)

Control flow is when your program changes direction based on a condition. Instead of always running every line, it chooses a path:

Normal flow:       Control flow:
────────────       ─────────────────────────────
Line 1             Line 1
Line 2             Is the condition true?
Line 3               YES → run Line A, skip Line B
Line 4               NO  → skip Line A, run Line B
                   Line 4

Think of it like a road with a fork. The condition is the signpost — it tells your program which road to take.

Real-life control flow examples

Situation Condition What happens
Entering a club Age ≥ 18? Yes → allowed in / No → turned away
Exam result Marks ≥ 50? Yes → pass / No → fail
Online order Item in stock? Yes → place order / No → show error
Traffic light Light is red? Yes → stop / No → go

JavaScript uses if, else, else if, and switch to express all of these.


2. The if Statement

The if statement is the most basic form of control flow. It runs a block of code only if a condition is true. If the condition is false, that block is simply skipped.

Syntax

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

How it works — step by step

1. Evaluate the condition inside ()
2. If condition is TRUE  → enter the {} block and run the code
3. If condition is FALSE → skip the {} block entirely
4. Continue with the rest of the program

Example — checking age

const age = 20;

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

console.log("Program continues here.");

// Output:
// You are an adult.
// Program continues here.

Now with a condition that is false:

const age = 15;

if (age >= 18) {
  console.log("You are an adult."); // ← skipped entirely
}

console.log("Program continues here.");

// Output:
// Program continues here.

The if block was completely skipped because 15 >= 18 is false.

More examples

const marks = 75;

if (marks >= 50) {
  console.log("You passed the exam!");
}

// ─────────────────────────────────────────
const temperature = 38;

if (temperature > 37) {
  console.log("You have a fever. Please rest.");
}

// ─────────────────────────────────────────
const isLoggedIn = true;

if (isLoggedIn) {
  console.log("Welcome back!");
}

🔑 Key point: The condition inside () always evaluates to either true or false. JavaScript will automatically convert values if needed — 0, "", null, undefined, and NaN are all treated as false. Everything else is treated as true.


3. The if-else Statement

The if alone only does something when the condition is true. The if-else adds a second path — something to do when the condition is false.

Syntax

if (condition) {
  // runs when condition is TRUE
} else {
  // runs when condition is FALSE
}

One of these two blocks always runs — never both, never neither.

Example — pass or fail

const marks = 43;

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

// Output: Result: Fail ✗

Step-by-step execution

marks = 43

Step 1: Check → is 43 >= 50?
Step 2: 43 >= 50 is FALSE
Step 3: Skip the if block
Step 4: Enter the else block
Step 5: Print "Result: Fail ✗"

More examples

// Even or odd
const number = 7;

if (number % 2 === 0) {
  console.log(number + " is Even");
} else {
  console.log(number + " is Odd");
}
// Output: 7 is Odd

// ─────────────────────────────────────────
// Login check
const password = "abc123";
const correctPassword = "mySecret";

if (password === correctPassword) {
  console.log("Access granted.");
} else {
  console.log("Wrong password. Try again.");
}
// Output: Wrong password. Try again.

// ─────────────────────────────────────────
// Temperature check
const temp = 22;

if (temp > 30) {
  console.log("It is hot outside.");
} else {
  console.log("The weather is comfortable.");
}
// Output: The weather is comfortable.

💡 Try this in your console:

const score = 85;
if (score >= 90) {
  console.log("Grade: A");
} else {
  console.log("Grade: B or below");
}
// Change the score value and run again

4. The else if Ladder

Sometimes you have more than two possible outcomes. The else if ladder lets you check multiple conditions in sequence, handling each case separately.

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 condition1 and condition2 are false AND condition3 is true
} else {
  // runs if ALL conditions above are false
}

JavaScript checks conditions from top to bottom. It stops at the first one that is true and runs that block. The else at the end is the fallback — it only runs if nothing matched.

Example — grading system

const 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 >= 50) {
  console.log("Grade: D");
} else {
  console.log("Grade: F — Please retake the exam");
}

// Output: Grade: C

Step-by-step execution for marks = 72

Step 1: Is 72 >= 90? → NO  → skip
Step 2: Is 72 >= 75? → NO  → skip
Step 3: Is 72 >= 60? → YES → run this block → print "Grade: C"
Step 4: Skip all remaining else-if and else blocks
Step 5: Continue with the rest of the program

Once a match is found, JavaScript exits the entire if-else ladder immediately. Conditions below the match are never checked.

Example — age categories

const age = 45;

if (age < 13) {
  console.log("Child");
} else if (age < 18) {
  console.log("Teenager");
} else if (age < 60) {
  console.log("Adult");
} else {
  console.log("Senior");
}

// Output: Adult

Example — traffic light

const light = "yellow";

if (light === "green") {
  console.log("Go!");
} else if (light === "yellow") {
  console.log("Slow down.");
} else if (light === "red") {
  console.log("Stop!");
} else {
  console.log("Unknown signal — proceed with caution.");
}

// Output: Slow down.

🔑 Order matters. In the grading example, if you put marks >= 50 first, a student with 95 marks would get Grade: D instead of Grade: A — because 95 >= 50 is true and the ladder stops there. Always put the most specific condition first.


5. The switch Statement

The switch statement is designed for situations where one variable is compared to many specific values. Instead of writing else if after else if, you list out cases cleanly.

Syntax

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

  case value2:
    // code for value2
    break;

  case value3:
    // code for value3
    break;

  default:
    // code if no case matched
}

How it works — step by step

1. Evaluate the expression once
2. Compare the result against each case value
3. Jump to the matching case and run its code
4. hit break → exit the switch block entirely
5. If no case matched → run the default block

Example — day of the week

const 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. Enter 1 to 7.");
}

// Output: Wednesday

What does break actually do?

break is essential in switch. Without it, JavaScript does not stop at the matched case — it falls through and runs every case below it until it hits a break or the end of the switch.

const day = 2;

switch (day) {
  case 1:
    console.log("Monday");
    // no break!
  case 2:
    console.log("Tuesday");
    // no break!
  case 3:
    console.log("Wednesday");
    break;
  case 4:
    console.log("Thursday");
    break;
}

// Output:
// Tuesday    ← matched here
// Wednesday  ← fell through because case 2 had no break!

This fall-through behaviour is almost always a bug. Always add break at the end of each case unless you have a specific reason not to.

The default case

default is like the else in an if-else ladder — it runs when no case matches:

const colour = "purple";

switch (colour) {
  case "red":
    console.log("Stop");
    break;
  case "green":
    console.log("Go");
    break;
  case "yellow":
    console.log("Slow down");
    break;
  default:
    console.log("Unknown colour: " + colour);
}

// Output: Unknown colour: purple

Grouping cases — same result for multiple values

You can stack cases together when they should produce the same output:

const day = "Saturday";

switch (day) {
  case "Monday":
  case "Tuesday":
  case "Wednesday":
  case "Thursday":
  case "Friday":
    console.log("Weekday — time to work!");
    break;

  case "Saturday":
  case "Sunday":
    console.log("Weekend — time to rest!");
    break;

  default:
    console.log("Not a valid day.");
}

// Output: Weekend — time to rest!

💡 Try this in your console:

const month = 2;
switch (month) {
  case 1: case 3: case 5: case 7:
  case 8: case 10: case 12:
    console.log("31 days"); break;
  case 4: case 6: case 9: case 11:
    console.log("30 days"); break;
  case 2:
    console.log("28 or 29 days"); break;
  default:
    console.log("Invalid month");
}

6. When to Use switch vs if-else

Both switch and if-else make decisions — but they are suited to different situations.

Use if-else when

// ✅ Checking ranges or comparisons (>, <, >=, <=)
if (marks >= 90) { ... }
else if (marks >= 75) { ... }

// ✅ Checking complex or multiple conditions
if (age >= 18 && hasID === true) { ... }

// ✅ Conditions involve different variables
if (temp > 35 || humidity > 80) { ... }

// ✅ You only have 2–3 conditions
if (isLoggedIn) { ... } else { ... }

Use switch when

// ✅ One variable compared to many specific values
switch (day) { case 1: ... case 2: ... }

// ✅ Menu options or command handling
switch (userChoice) {
  case "start":  startGame();  break;
  case "pause":  pauseGame();  break;
  case "quit":   quitGame();   break;
}

// ✅ Status codes or fixed categories
switch (statusCode) {
  case 200: console.log("OK");           break;
  case 404: console.log("Not Found");    break;
  case 500: console.log("Server Error"); break;
}

Side-by-side comparison

if-else switch
Checks Any condition (ranges, logic) Exact value matches only
Condition type >, <, >=, &&, `
Multiple variables ✅ Yes ❌ One expression only
Readability Better for 2–3 conditions Better for 5+ fixed values
Fall-through ❌ Not possible ✅ Possible (needs break)
Default fallback else default

The quick rule

Range or complex logic → if-else Many exact values of one variable → switch


Diagrams

if-else Decision Flowchart

┌─────────────────────────────────────────────────────────────┐
│               IF-ELSE DECISION FLOWCHART                    │
│                                                             │
│                    ┌────────────┐                           │
│                    │   Start    │                           │
│                    └─────┬──────┘                           │
│                          ↓                                  │
│                 ┌────────────────┐                          │
│                 │  Condition     │                          │
│                 │  marks >= 50?  │                          │
│                 └───┬────────┬───┘                          │
│                     │        │                              │
│                   TRUE      FALSE                           │
│                     ↓        ↓                              │
│             ┌────────────┐  ┌────────────┐                  │
│             │   "Pass"   │  │   "Fail"   │                  │
│             └─────┬──────┘  └─────┬──────┘                  │
│                   └────────┬───────┘                        │
│                            ↓                               │
│                    ┌────────────┐                           │
│                    │  Continue  │                           │
│                    └────────────┘                           │
│                                                             │
│  else-if ladder (multiple conditions):                      │
│                                                             │
│           ┌──────────────┐                                  │
│           │ marks >= 90? ├── YES → "Grade A"                │
│           └──────┬───────┘                                  │
│                  │ NO                                        │
│           ┌──────┴───────┐                                  │
│           │ marks >= 75? ├── YES → "Grade B"                │
│           └──────┬───────┘                                  │
│                  │ NO                                        │
│           ┌──────┴───────┐                                  │
│           │ marks >= 60? ├── YES → "Grade C"                │
│           └──────┬───────┘                                  │
│                  │ NO                                        │
│           ┌──────┴───────┐                                  │
│           │    else      │──────→ "Grade F"                 │
│           └──────────────┘                                  │
│                                                             │
│  ✦ Checks top to bottom — stops at first TRUE condition     │
│  ✦ The else block only runs if nothing above matched        │
└─────────────────────────────────────────────────────────────┘

switch-case Branching Diagram

┌─────────────────────────────────────────────────────────────┐
│             SWITCH-CASE BRANCHING DIAGRAM                   │
│                                                             │
│   switch (day)                                              │
│         │                                                   │
│         ├── case 1  → "Monday"    → break ──┐              │
│         │                                   │              │
│         ├── case 2  → "Tuesday"   → break ──┤              │
│         │                                   │              │
│         ├── case 3  → "Wednesday" → break ──┤              │
│         │                                   │              │
│         ├── case 4  → "Thursday"  → break ──┤              │
│         │                                   │              │
│         ├── case 5  → "Friday"    → break ──┤              │
│         │                                   │              │
│         ├── case 6  → "Saturday"  → break ──┤              │
│         │                                   │              │
│         ├── case 7  → "Sunday"    → break ──┤              │
│         │                                   │              │
│         └── default → "Invalid"   ──────────┘              │
│                                   │                         │
│                              EXIT switch                    │
│                                                             │
│  What break does:                                           │
│  ─────────────────────────────────────────                  │
│  WITH break:    case 3 matches → runs "Wednesday"           │
│                 → break → exits immediately ✓               │
│                                                             │
│  WITHOUT break: case 3 matches → runs "Wednesday"           │
│                 → falls into case 4 → "Thursday"            │
│                 → falls into case 5 → "Friday"  ← bug!     │
│                                                             │
│  ✦ Always add break unless you intentionally want fallthrough│
└─────────────────────────────────────────────────────────────┘

Practice Assignment

Try these three exercises in your browser console or in a .js file.


Task 1 — Positive, Negative, or Zero

Write a program that takes a number and tells you whether it is positive, negative, or zero.

const number = -7; // change this value and test

if (number > 0) {
  console.log(number + " is Positive");
} else if (number < 0) {
  console.log(number + " is Negative");
} else {
  console.log("The number is Zero");
}

// Test with: -7 → "Negative"
// Test with:  0 → "Zero"
// Test with: 15 → "Positive"

Why if-else here? Because we are checking ranges and comparisons (> 0, < 0). These are conditions that switch cannot handle — it only checks exact equality.


Task 2 — Day of the Week using switch

Write a program that prints the name of the day based on a number (1 = Monday, 7 = Sunday).

const dayNumber = 5; // change this value and test

switch (dayNumber) {
  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! Please enter a number between 1 and 7.");
}

// Test with: 5 → "Friday"
// Test with: 7 → "Sunday"
// Test with: 9 → "Invalid!"

Why switch here? Because we are comparing one variable (dayNumber) against many exact values (1 through 7). This is exactly what switch is designed for — it is more readable than writing seven else if blocks.


Task 3 — Bonus: Grade Calculator

Combine both — use an if-else ladder and explain your reasoning.

const marks = 68;

if (marks >= 90) {
  console.log("Grade: A — Excellent!");
} else if (marks >= 75) {
  console.log("Grade: B — Good job!");
} else if (marks >= 60) {
  console.log("Grade: C — Satisfactory");
} else if (marks >= 50) {
  console.log("Grade: D — Needs improvement");
} else {
  console.log("Grade: F — Please retake the exam");
}

// Output: Grade: C — Satisfactory

Why if-else and not switch here? Because grades depend on ranges (>= 90, >= 75), not exact values. switch can only check if marks === 90 or marks === 75, not whether marks fall within a range. For ranges, if-else is always the right choice.


Quick Reference

// ─── if ───────────────────────────────────────────────────
if (condition) {
  // runs only when condition is true
}

// ─── if-else ──────────────────────────────────────────────
if (condition) {
  // true path
} else {
  // false path
}

// ─── else-if ladder ───────────────────────────────────────
if (condition1) {
  // first match
} else if (condition2) {
  // second match
} else if (condition3) {
  // third match
} else {
  // no match — fallback
}

// ─── switch ───────────────────────────────────────────────
switch (value) {
  case "a":
    // code for "a"
    break;
  case "b":
    // code for "b"
    break;
  default:
    // no match fallback
}

// ─── Grouped cases ────────────────────────────────────────
switch (value) {
  case "x":
  case "y":
    // runs for both "x" and "y"
    break;
}

Wrapping Up

Control flow is what makes programs intelligent. Without it, your code does the same thing every single time — with it, your program can respond to data, user input, and real-world conditions.

Here is what you learned:

  • Control flow means your program can choose different paths based on conditions

  • if runs a block only when a condition is true

  • if-else gives you two paths — one for true, one for false

  • else if ladder handles multiple conditions in sequence, top to bottom, first match wins

  • switch cleanly handles one variable compared against many exact values — always use break

  • Use if-else for ranges and complex logic; use switch for many exact values of one variable

Start with the assignment exercises above, change the values and re-run them, and you will be comfortable with all of these in no time.

Happy coding! 🚀


The fastest way to learn control flow: pick a real decision from your daily life (what to wear, what to eat) and try to write it as an if-else ladder in JavaScript.