DEV Community

Cover image for Control Flow in JavaScript: if, else, and switch Explained with Real Examples
Janmejai Singh
Janmejai Singh

Posted on

Control Flow in JavaScript: if, else, and switch Explained with Real Examples

Programming is not just about writing code β€” it's about making decisions. Just like humans decide what to do based on situations, programs use control flow to choose different paths depending on conditions.

In this article, you'll learn the core control flow tools in JavaScript:

  • if
  • if-else
  • else if
  • switch

We'll use simple real-life analogies and short programs to make everything crystal clear. Let's dive in! πŸš€


🚦 What Is Control Flow?

Control flow determines the order in which code is executed.

Normally, code runs line by line from top to bottom. But sometimes we want it to branch based on a condition.

Think of a traffic signal:

  • πŸ”΄ Red β†’ Stop
  • 🟑 Yellow β†’ Slow down
  • 🟒 Green β†’ Go

JavaScript works the same way β€” it checks a condition and decides which block of code to run.


βœ… The if Statement

The if statement runs a block of code only when a condition is true.

Syntax

if (condition) {
  // runs only if condition is true
}
Enter fullscreen mode Exit fullscreen mode

Example β€” Voting Eligibility

let age = 20;

if (age >= 18) {
  console.log("You are eligible to vote.");
}
Enter fullscreen mode Exit fullscreen mode

How it works, step by step:

  1. JavaScript evaluates age >= 18
  2. Since 20 >= 18 is true, the message prints
  3. If it were false, nothing would happen

πŸ”€ The if-else Statement

Use if-else when you want one thing to happen if true, and another if false.

Syntax

if (condition) {
  // runs if true
} else {
  // runs if false
}
Enter fullscreen mode Exit fullscreen mode

Example β€” Even or Odd

let number = 7;

if (number % 2 === 0) {
  console.log("Number is Even");
} else {
  console.log("Number is Odd");
}
Enter fullscreen mode Exit fullscreen mode

Output:

Number is Odd
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ % is the modulo operator β€” it returns the remainder after division. If it's 0, the number is even.


πŸͺœ The else if Ladder

Use else if when you have multiple conditions to check in sequence.

Syntax

if (condition1) {
  // ...
} else if (condition2) {
  // ...
} else {
  // fallback
}
Enter fullscreen mode Exit fullscreen mode

Example β€” Student Grading System

let marks = 75;

if (marks >= 90) {
  console.log("Grade A");
} else if (marks >= 75) {
  console.log("Grade B");
} else if (marks >= 50) {
  console.log("Grade C");
} else {
  console.log("Fail");
}
Enter fullscreen mode Exit fullscreen mode

Output:

Grade B
Enter fullscreen mode Exit fullscreen mode

Step-by-step execution:

Step Condition Result
1 marks >= 90? ❌ False
2 marks >= 75? βœ… True β†’ prints "Grade B"
3 (skipped) β€”

⚠️ Once a condition is true, the rest are skipped entirely.


πŸ” The switch Statement

Use switch when one variable can have many specific values.

Instead of chaining multiple if-else blocks, switch gives you cleaner, more readable code.

Syntax

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

  case value2:
    // code
    break;

  default:
    // fallback code
}
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

Output:

Wednesday
Enter fullscreen mode Exit fullscreen mode

⚠️ Why break Matters in Switch

Without break, JavaScript will fall through and keep running the next cases!

// Missing break β€” BAD example
switch (day) {
  case 3:
    console.log("Wednesday");
  case 4:
    console.log("Thursday"); // This runs too!
}
Enter fullscreen mode Exit fullscreen mode

Output (unintended):

Wednesday
Thursday
Enter fullscreen mode Exit fullscreen mode

Always add break after each case unless fall-through is intentional.


πŸ†š When to Use switch vs if-else

Scenario Best Choice
Checking value ranges (marks > 90) if-else
Checking one variable against many fixed values switch
Complex multi-variable conditions if-else
Menu options, day names, status codes switch

Quick Rule of Thumb

  • Use if-else for ranges and complex logic:
  marks > 90
  marks > 75
  marks > 50
Enter fullscreen mode Exit fullscreen mode
  • Use switch for exact, fixed values:
  1 β†’ Login
  2 β†’ Register
  3 β†’ Exit
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Practice Programs

Program 1: Positive, Negative, or Zero

let number = -5;

if (number > 0) {
  console.log("Positive number");
} else if (number < 0) {
  console.log("Negative number");
} else {
  console.log("Zero");
}
Enter fullscreen mode Exit fullscreen mode

Why if-else? We're checking ranges (> 0, < 0), not fixed values.


Program 2: Print Day Name 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");
}
Enter fullscreen mode Exit fullscreen mode

Why switch? The variable day can only be one specific number at a time.


πŸ“Š Flowchart: How if-else Works

         Start
           |
       Condition?
      /          \
   true          false
    |               |
 Block A         Block B
    |               |
         End
Enter fullscreen mode Exit fullscreen mode

🌿 Flowchart: How switch Branches

         value
           |
        switch
     /  |  |  |  \
    1   2   3   4   5
    |   |   |   |   |
   Mon Tue Wed Thu Fri
Enter fullscreen mode Exit fullscreen mode

🧠 Key Takeaways

Statement Use When
if One condition to check
if-else Two possible outcomes
else if Multiple conditions in a chain
switch One variable, many fixed values

Control flow statements give your program the power to think and decide. Almost every real-world application β€” from login pages to e-commerce carts β€” relies on them heavily.


πŸš€ What's Next?

Now that you understand control flow, you're ready to explore:

  • Loops (for, while) β€” to repeat actions
  • Functions β€” to organize and reuse logic
  • Arrays & Objects β€” to manage collections of data

Found this helpful? Drop a ❀️, share it with a fellow learner, or leave a comment below with your questions!

Happy coding! πŸ§‘β€πŸ’»

Top comments (0)