Skip to main content

Command Palette

Search for a command to run...

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

Learn how JavaScript programs make decisions using if, else if, and switch statements with simple examples.

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

CSE student documenting my learning in databases, networking, and web fundamentals.

In the previous articles, we learned two important things.

  1. First, we learned how to store information using variables.

  2. Then we learned how to perform operations on that information using operators.

But this is only the beginning of our programming journey.

Now an important question arises. What if a program needs to make decisions? For example:

  • If a user is 18 or older, allow them to sign up.

  • If today is Sunday, show a holiday message.

In such cases, our program needs to choose what to do next. And this is exactly where Control Flow comes in.


What Does Control Flow Mean?

Control flow simply means:

The order in which a program executes instructions.

By default, JavaScript executes code from top to bottom.

Example:

console.log("Step 1");
console.log("Step 2");
console.log("Step 3");

The output will be:

Step 1
Step 2
Step 3

As expected, right? But real programs are not always this simple. Sometimes, the program must choose between different paths.

Sounds complex? Let us take an example.

Think of it like a path.

  • If you want to go to City A, you choose Path A.

  • If you want to go to City B, you choose Path B.

Similarly, JavaScript decides which path to follow based on conditions. And to do that, we use control flow statements.

The most common ones are:

  • if

  • if...else

  • else if

  • switch

Let's start with the most basic one.


1️⃣ The if Statement

The if statement allows a program to run some code only if a condition is true.

Before we see an example, let us first understand the basic syntax of the if statement.

Syntax

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

Let’s understand what this means.

  • if is the keyword that starts the decision.

  • Inside the parentheses ( ), we write a condition.

  • If that condition becomes true, the code inside the curly braces { } runs.

  • If the condition becomes false, JavaScript simply skips that block of code.

Now let us see this in action.

Example:

let age = 20;

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

Let’s understand what happens step by step.

First, JavaScript evaluates the condition:

age >= 18

Since the value of age is 20, the condition becomes:

20 >= 18 → true

Because the condition is true, JavaScript executes the code inside the block.

So the output will be:

You are eligible to vote.

Now let’s try changing the value.

let age = 15;

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

Now JavaScript evaluates the condition again:

15 >= 18 → false

Since the condition is false, the code inside the block will not run, so nothing will be printed in the console.

Analogy:

You can think of the if statement like a gate.

  • If the condition is true, the gate opens and the code inside runs.

  • If the condition is false, the gate stays closed and the code is skipped.

Flowchart

Try it Yourself

Let's do a small experiment.

let temperature = 35;

if (temperature > 30) {
  console.log("It's a hot day.");
}

Before running the code, pause for a moment and think. What do you think will be printed?
Now change the value of temperature to 25 and run the code again.

Observe how the result changes. This is how programs start making decisions based on conditions.


So far, everything looks good, right? But what if we want the program to do something when the condition is false?
Right now, if the condition becomes false, JavaScript simply skips the code and moves ahead. But sometimes we want the program to take another action instead.
That’s exactly where the if...else statement helps us.


2️⃣ The if...else Statement

The if...else statement allows a program to choose between two possible actions.

So instead of simply skipping the code when a condition is false, the program can perform an alternative action. This means the program can respond differently depending on whether a condition is true or false.

Before we see an example, let us first understand the basic syntax of the if...else statement.

Syntax

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

Let’s understand what this means.

  • The if block runs when the condition is true.

  • The else block runs when the condition is false.

  • Only one of these blocks will execute.

Example

let age = 16;

if (age >= 18) {
  console.log("You are eligible to vote.");
} else {
  console.log("You are not eligible to vote yet.");
}

Now let’s see how JavaScript executes this code step by step.

First, JavaScript evaluates the condition:

age >= 18

Since the value of age is 16, the condition becomes:

16 >= 18 → false

Because the condition is false, the code inside the if block is skipped. Instead, JavaScript executes the code inside the else block.

So the output will be:

You are not eligible to vote yet.

Now let’s try changing the value.

let age = 20;

if (age >= 18) {
  console.log("You are eligible to vote.");
} else {
  console.log("You are not eligible to vote yet.");
}

Now JavaScript evaluates the condition again:

20 >= 18 → true

This time the condition is true, so the if block runs and the else block is skipped.

The output will be:

You are eligible to vote.

Analogy:

You can think of the if...else statement like reaching a fork in the road. At that point, you must choose one of two directions.

  • If the condition is true, the program takes one path.

  • If the condition is false, it takes the other path.

Flowchart

Try it Yourself

Let’s try a small experiment.

let number = 8;

if (number % 2 === 0) {
  console.log("The number is even.");
} else {
  console.log("The number is odd.");
}

Before running the code, pause for a moment and think. What do you think the output will be? Now try changing the value of number to 7 and run the code again.

Observe how the output changes. This is how programs make decisions and perform different actions based on conditions.


Now we understand how a program can choose between two possible outcomes. But what if there are more than two possibilities?

For example:

  • A student can get Grade A, B, C, or Fail.

  • A number can be positive, negative, or zero.

Handling these situations using only if...else can quickly become messy. That’s where the else if ladder comes in.


3️⃣ The else if Ladder

So far, we learned how a program can choose between two possible outcomes using if...else. But real-life situations often involve more than just two possibilities.

For example:

  • A student can get Grade A, B, C, or Fail.

  • A number can be positive, negative, or zero.

  • A person can be a child, a teenager, or an adult.

In such cases, using only if...else is not enough. We need a way to check multiple conditions one after another.

That’s where the else if ladder comes in. Let us first understand the basic structure of an else if ladder.

Syntax

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

Let’s understand what happens here.

  • JavaScript first checks condition1.

  • If it is true, that block runs and the rest of the ladder is skipped.

  • If it is false, JavaScript moves to the next condition.

  • This process continues until a condition becomes true.

  • If none of the conditions are true, the else block runs.

This is why it is called a ladder. JavaScript checks each step one by one.

Example

Let’s write a program that checks whether a number is positive, negative, or zero. Don't worry, it's very easy.

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

Now let us see how JavaScript evaluates this step by step.

First condition:

number > 0

Since the value of number is -5, the condition becomes:

-5 > 0 → false

So JavaScript moves to the next condition.

Second condition:

number < 0

Now it becomes:

-5 < 0 → true

Since this condition is true, the output will be:

The number is negative.

Note:

In an else if ladder, JavaScript checks conditions from top to bottom.
As soon as it finds the first true condition, it runs that block and skips the rest.
Only one block will execute.

Now, try experimenting with values and see the results.

Analogy

You can think of the else if ladder like a security checkpoint. At each checkpoint, a guard asks a question.

  • If the answer matches, you go through that gate and stop there.

  • Otherwise, you move to the next checkpoint.

Similarly, JavaScript keeps checking conditions one by one until it finds a match.

Flowchart

Try it Yourself

Let’s experiment with a grading system.

let marks = 82;

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

Before running the code, pause for a moment and think. Which condition do you think will be true?

Try changing the value of marks to:

  • 95

  • 60

  • 40

Observe how the output changes depending on the conditions. This is how programs evaluate multiple possibilities step by step.


Now we know how to handle multiple conditions using the else if ladder. But sometimes we are comparing one variable against many specific values.

For example:

  • Checking the day of the week

  • Handling menu options

In such situations, writing many else if statements can become repetitive and harder to read. JavaScript provides another structure for this called the switch statement.


4️⃣ The switch Statement

So far, we have seen how to handle multiple conditions using the else if ladder. But sometimes we are comparing one variable against many specific values.

For example:

  • Checking the day of the week

  • Handling menu options

  • Selecting a user role

In situations like these, writing many else if statements can make the code look repetitive. JavaScript provides another control structure for this called the switch statement.

Syntax

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

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

  case value3:
    // code runs if expression === value3
    break;

  default:
    // code runs if none of the cases match
}

Let’s understand what happens here.

  • The switch statement checks the value of an expression.

  • It then compares that value with each case.

  • When a matching case is found, the corresponding code runs.

  • The break statement stops the execution of the switch block.

If none of the cases match, the default case runs.

Example

Let’s write a program that prints the 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;

  default:
    console.log("Weekend");
}

Let’s see how JavaScript evaluates this.

The value of day is:

3

JavaScript compares this value with each case.

3 === 1 → false
3 === 2 → false
3 === 3 → true

Since the third case matches, JavaScript executes this block:

Wednesday

Then the break statement stops the switch execution.

Important: Why break is Needed

The break statement tells JavaScript:

“Stop here and exit the switch block.”

Without break, JavaScript continues executing the next cases.

Let’s see what happens if we remove break.

Example

let day = 2;

switch (day) {
  case 1:
    console.log("Monday");

  case 2:
    console.log("Tuesday");

  case 3:
    console.log("Wednesday");
}

What do you think will happen? Pause for a moment and think.

Now let’s see the output:

Tuesday
Wednesday

Why did this happen? Because once a matching case is found, JavaScript continues executing the next cases until it encounters a break or the switch block ends.

This behavior is called fall-through.

Analogy

You can think of a switch statement like pressing a button in an elevator. Each floor is like a case.

  • When you press a floor button, the elevator goes directly to that floor.

  • But if there were no stop mechanism, the elevator would keep moving past other floors.

The break statement works like the stop command — it tells the program where to stop.

Flowchart

Try it Yourself

Let’s try a small experiment.

let role = "admin";

switch (role) {
  case "admin":
    console.log("Full access granted");
    break;

  case "editor":
    console.log("Can edit content");
    break;

  case "viewer":
    console.log("Read-only access");
    break;

  default:
    console.log("Unknown role");
}

Before running the code, pause for a moment and think. What do you think the output will be?

Now try changing the value of role to:

  • "editor"

  • "viewer"

  • "guest"

Observe how the result changes.


When to Use switch vs if...else

Both switch and if...else can be used for decision making. But they are useful in slightly different situations.

Use if...else when:

You are working with ranges or complex conditions

Example:

marks >= 90
age > 18
temperature < 0

Use switch when:

You are comparing one variable against multiple fixed values

Example:

day of the week
menu options
user roles

Simple rule to remember:

  • Ranges → if...else

  • Fixed values → switch

Note:

In practice, many developers often prefer if...else because it is flexible and works in almost every situation.
However, switch can make code cleaner when you are comparing one value against many fixed options.


Wrapping Up

In this article, we explored how JavaScript programs make decisions using control flow statements. We started by understanding what control flow means — the order in which a program executes instructions.

Then we looked at the different ways JavaScript can choose between multiple paths:

  • The if statement, which runs code only when a condition is true.

  • The if...else statement, which allows a program to choose between two possible outcomes.

  • The else if ladder, which helps check multiple conditions step by step.

  • The switch statement, which is useful when comparing one value against many fixed options.

These control structures allow programs to behave intelligently by deciding what action to take depending on a condition. Without control flow, a program would simply execute every line from top to bottom without making any decisions.

Before moving ahead, take a few minutes to experiment with the examples in this article. Try changing values, modifying conditions, and observing how the output changes.

That’s one of the best ways to truly understand how control flow works.


What's Next?

Now that we know how JavaScript makes decisions, the next natural step is learning how to organize and reuse code.

Imagine writing the same piece of code again and again. That would quickly become messy and difficult to maintain. Want to know how we can reuse our code? Stay tuned for the upcoming blog.


⬅ Previous Article: Operators in JavaScript
➡ Next Article: Functions in JavaScript

JavaScript Foundations

Part 9 of 11

This series documents my journey of learning JavaScript from the ground up. Each article explains core JavaScript concepts in a beginner-friendly way with simple examples and practical explanations. Topics include variables, operators, control flow, functions, arrow functions, arrays, objects, and more. If you're starting your JavaScript journey, this series will help you build a strong foundation step by step.

Up next

JavaScript Operators: The Basics You Need to Know

In the previous article, we learned how to store information using variables. But learning how to store information is only the first step in our programming journey. If we write: let a = 10; let b =