Skip to main content

Command Palette

Search for a command to run...

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

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

Imagine waking up in the morning and looking out the window. If it's raining, you grab an umbrella. If it's sunny, you reach for your sunglasses. You just made a decision based on a specific condition.

Programming is exactly the same. We don't want our code to do the exact same thing every single time it runs, we want it to react to different situations.

In my previous blog, we covered JavaScript operators -> arithmetic, comparison, logical, and assignment. We learned that variables are the nouns and operators are the verbs in our code. Now, it's time to take those verbs and use them to make intelligent decisions. As we push forward through our 2026 Web Dev Cohort, mastering these core concepts is what will separate a static page from a dynamic, interactive application.

Let's dive into Control Flow

What is Control Flow?

By default, JavaScript reads our code like a book: from top to bottom, line by line. Control flow is simply the order in which your computer executes statements in a script.

When we introduce decision-making structures (like if, else, and switch), we change that default flow. We tell JavaScript to skip certain lines, repeat others, or choose between multiple paths based on the data it receives.

Here is a very simple example of altering the flow:

let isHungry = true;

if(isHungry){
  console.log("Time to eat") 
}

console.log("Back to coding")

Step-by-step Execution

  1. JavaScript creates a variable isHungry and sets it to true.

  2. It hits the if statement and checks the condition inside the parentheses. Is isHungry true? Yes.

  3. Because the condition is true, it enters the curly braces {} and prints "Time to eat".

  4. It exits the block and moves to the next line, printing "Back to coding".

If isHungry was false, it would completely skip the code inside the curly braces

The if Statement: The Gatekeeper

The if statement is the most basic building block of control flow. It evaluates a condition, and if that condition is true, it runs a specific block of code.

let userAge = 20

if(userAge >= 18){
  console.log("Welcome to the website");
}

Step-by-step Execution

  1. We set userAge to 20.

  2. The if statement checks: is 20 >= 18?

  3. This evaluates to true.

  4. JavaScript runs the console.log inside the block.

The if-else Statement : The Fork in the Road

What if we want something specific to happen when the condition is false ? That's where else comes in. It provides a fallback path.

let age = 16

if(age >= 18){
  console.log("You are eligible to vote")
} else {
  console.log("Sorry, you are too young to vote")
}

Step-by-step Execution

  1. age is 16.

  2. The if condition checks: is 16 >= 18?

  3. This is false

  4. JavaScript immediately skips the if block and jumps into the else block.

  5. It prints "Sorry, you are too young to vote."

Important: Only ONE block will ever execute. It is impossible for both the if and the else block to run in the same pass.

Visual Flow of an If-Else Decision

The else if Ladder : Multiple Choices

Sometimes a simple yes or no isn't enough. When you have multiple specific conditions to check, you can chain them together using an else if ladder.

let studentMarks = 85

if(studentMarks >= 90){
  console.log("Grade: A")
} else if (studentMarks >= 80) {
  console.log("Grade: B")
} else if (studentMarks >= 70) {
  console.log("Grade: C")
} else {
  console.log("Grade: F")
}

Step-by-step Execution

  1. studentMarks is 85.

  2. It checks the first condition: 85 >= 90? (False). Skips.

  3. It checks the next condition: 85 >= 80? (True).

  4. It prints "Grade: B"

  5. Crucial Concept: Because it found a true condition, it stops checking, It entirely skips the >= 70 check and the else block.

JavaScript checks top-to-bottom and stops at the very first true condition it finds.

The switch Statement : The Clean Matchmaker

When you need to check a single variable against many exact values, writing a giant else if ladder can get messy. The switch statement is a cleaner alternative for this exact scenario.

let 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;
  default:
    dayName = "Invalid day"
}

console.log(dayName); // Output: Wednesday

How it works

  1. The switch grabs the variable dayNumber (which is 3).

  2. It looks for a case that exactly matches 3

  3. It finds case 3: and executes the code inside it, setting dayName to "Wednesday"

  4. It hits the break keyword. This tells JavaScript to completely exit the switch block.

Common Mistake: The Fall-Through If you forget to write break;, JavaScript will keep executing the code for every case below it, even if the values don't match, This is called fall-through. Always remember your breaks unless you are intentionally grouping cases together. The default keyword acts just like an else -> it runs if absolutely no matches are found.

Visual Structure of a Switch Statement

When to Use Which?

Choosing the right structure is a hallmark of writing clean, maintainable code.

Use if-else when:

  • You are checking for ranges (e.g., age > 18 or marks < 50).

  • You are evaluating complex logic with multiple different variables (e.g., if (isLoggedIn && hasPremiumAccount)).

  • The condition involves truthy/falsy evaluations.

Use switch when:

  • You are checking one single variable.

  • You are looking for exact value matches (e.g., status === 'pending').

  • You have a large number of possible conditions and want cleaner readability.

Assignment Programs

To solidify these concepts, let's look at two practical examples.

Program 1: Check if a number is positive, negative, or zero

Structure Chosen: if-else Why? We are checking ranges (greater than zero, less than zero), making if-else the perfect fit.

let number = -5

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 exactly zero")
}

Program 2: Print the day of the week

Structure Chosen: switch Why? We have one variable (day) and we are checking it against strict, exact values (Monday, Tuesday etc.)

let dayAbbreviation = "Fri"

switch(dayAbbreviation){
  case "Mon":
    console.log("Monday")
    break;
  case "Fri":
    console.log("Friday")
    break;
  case "Sun":
    console.log("Sunday")
    break;
  default:
    console.log("Just another day")
}

Summary

Control flow is what allows our programs to make decisions instead of running line-by-line without thinking.

  • if runs a block only when a condition is true.

  • if-else creates two possible paths.

  • else if helps us handle multiple specific conditions.

  • switch is cleaner when checking one variable against exact values.

  • break prevents unwanted fall-through inside switch.

Writing this out really helped me understand how simple conditions can completely change the direction of a program.

Understanding control flow means you are no longer just writing instructions. You are building logic.

Thanks for reading. In the next blog, we will take this logic and wrap it inside reusable blocks of code as we explore functions and the difference between function declarations and function expressions.

More from this blog