Skip to main content

Command Palette

Search for a command to run...

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

Updated
10 min readView as Markdown
Control Flow in JavaScript: If, Else, and Switch Explained
R
the topics and concepts which i learn and get more fascinated i write about them here...

Every day, we make hundreds of decisions. "If it is raining, I will take an umbrella. Otherwise, I will not take it with me". We make many more similar decision like this. This is exactly what control flow is in programming, it is the ability to make decisions inside our code.
Without control flow, a program would just run every line from top to bottom without choosing different paths. With control flow, our code can see the conditions and react to it and then choose different actions, and behave intelligently based on data.

What is a Control Flow?

Control flow is the order in which our program runs its lines of code. Using statements like if, else, and switch, we can make our code choose which path to follow based on the conditions given.

The if Statement

The if statement is the simplest way to make decisions. It allows to Run a particular block of code only if the condition is true.

The syntax of if:

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

Example:

let age = 20;


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


// Output: You are eligible to vote!

Since age is 20, the condition age >= 18 is true, so the message gets prints. If age was 15, the condition would be false and nothing would happen.

The if-else Statement

Now we saw in the if statement that if the condition is true execute the code inside the if block, but what if the condition is false then which block to execute here comes the else statement. Combining forms the if-else statement. It provides an alternative path.

Syntax:

if (condition) {
  // Runs if condition is TRUE
} else {
  // Runs if condition is FALSE
}

Example:

let marks = 45;


if (marks >= 50) {
  console.log('Congratulations! You passed.');
} else {
  console.log('Sorry, you failed. Keep trying!');
}


// Output: Sorry, you failed. Keep trying!

Because marks is 45, which is less than 50, the condition is false, so JavaScript runs the else block instead.

Flowchart:

The else if Ladder

What if we have more than 2 outcomes. Then we can chain the multiple conditions using else if . We can think of it as checking conditions one by one until one matches.

Syntax:

if (condition1) {
  // Runs if condition1 is true
} else if (condition2) {
  // Runs if condition2 is true
} else if (condition3) {
  // Runs if condition3 is true
} else {
  // Runs if NONE of the above conditions are true
}

Example:

let 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');  // ← This runs
} else if (marks >= 40) {
  console.log('Grade: D');
} else {
  console.log('Grade: F');
}


// Output: Grade: C

Javascript checks each condition from top to bottom. As soon as one condition is true , it runs that block and skips the rest. Hence it never checks the conditions after finding a match

Important: Only one code block Runs

Even if multiple conditions could be true, only the FIRST matching block runs. JavaScript stops checking as soon as it finds a match.

Real-Life Example:

let hour = 14;  // 2 PM in 24-hour format


if (hour < 12) {
  console.log('Good Morning!');
} else if (hour < 17) {
  console.log('Good Afternoon!');  // ← This runs (14 < 17)
} else if (hour < 21) {
  console.log('Good Evening!');
} else {
  console.log('Good Night!');
}


// Output: Good Afternoon!

The switch Statement

The switch statement is another way to handle multiple conditions, but it works differently from else if. Instead of evaluating ranges or complex expressions, switch checks if a value exactly matches one of the several predefined cases.

We can think of switch statement as a vending machine, we press a button(our value), and the machine runs the eact action for the particular button.

Syntax:

switch (expression) {
  case value1:
    // Code runs if expression === value1
    break;
  case value2:
    // Code runs if expression === value2
    break;
  default:
    // Code runs if no case matches
}

Example:

let day = 3;


switch (day) {
  case 1:
    console.log('Monday');
    break;
  case 2:
    console.log('Tuesday');
    break;
  case 3:
    console.log('Wednesday');  // ← This runs
    break;
  case 4:
    console.log('Thursday');
    break;
  case 5:
    console.log('Friday');
    break;
  default:
    console.log('Weekend!');
}


// Output: Wednesday

Flowchart:

Understanding break in switch

The break keyword is an important keyword in a switch statement. It tells Javascript to stop executing and exit the switch block. Without break, Javascript will fall through, meaning it will keep running the code for every case below the matched one.

What happens without break?



let day = 2;


switch (day) {
  case 1:
    console.log('Monday');
  case 2:
    console.log('Tuesday');   // ← Matches here...
  case 3:
    console.log('Wednesday'); // ← ...but keeps running!
  case 4:
    console.log('Thursday');  // ← ...and this too!
}


// Output:
// Tuesday
// Wednesday
// Thursday

Always use break!!

Without break, JavaScript 'falls through' all the cases below the match. This is almost always a bug. Always add break at the end of each case(unless we want the intentionally want the fall-through behavior)

The correct version with break;

let day = 2;


switch (day) {
  case 1:
    console.log('Monday');
    break;
  case 2:
    console.log('Tuesday');   // ← Matches here
    break;                    // ← Exits the switch immediately
  case 3:
    console.log('Wednesday'); // ← Skipped
    break;
}


// Output: Tuesday

The default case

The default case is like the else in an if-else chain. It runs when no case matches the expression.



let color = 'purple';


switch (color) {
  case 'red':
    console.log('Stop!');
    break;
  case 'green':
    console.log('Go!');
    break;
  default:
    console.log('Unknown color: ' + color);  // ← This runs
}


// Output: Unknown color: purple

switch vs if-else. When to use what?

Both the switch and if-else can often solve the same problem. But each has its sweet spot. here is how we can choose the correct one.

Situaution Use if-else Use switch
Checking ranges (eg. marks > 80) Best choice Not Suitable
Checking exact values (eg. day === 3) Works Cleaner choice
Multiple exact matches Gets long and messy Much cleaner
Complex boolean logic ( &&, )
Checking one variable, many values Repetitive Perfect fit
Default behaviour Use else Use default

Example:
Using if-else

// Works, but repetitive...
if (day === 1) { console.log('Monday'); }
else if (day === 2) { console.log('Tuesday'); }
else if (day === 3) { console.log('Wednesday'); }
else if (day === 4) { console.log('Thursday'); }
else if (day === 5) { console.log('Friday'); }
else { console.log('Weekend'); }

Using switch(much cleaner)

// Much cleaner for exact value matching
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');
}

Rule:

Use if-else when the conditions involve ranges, calculations, or multiple variables. Use switch when we are checking one variable against several exact values, it is easier to read.

Practice Assignment:

Task 1 - Positive, Negative, or Zero

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

let number = -7;  // Try changing this value!


if (number > 0) {
  console.log(number + ' is Positive');
} else if (number < 0) {
  console.log(number + ' is Negative');  // ← Output: -7 is Negative
} else {
  console.log('The number is Zero');
}

Here we used the if-else control statement because we needed to compare the value of number which would not have been possible in switch

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).

let dayNumber = 5;  // Try 1 through 7


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;  // Output: Friday
  case 6: console.log('Saturday');  break;
  case 7: console.log('Sunday');    break;
  default: console.log('Invalid day number. Enter 1-7.');
}

Here, as we have only one variable and for each input we need to compare the days, so using switch made the code look much cleaner and easy to understand.

Task 3 - Season Finder

Write a program that tells you the season based on a month number (1-12).

let month = 8;  // August


if (month >= 3 && month <= 5) {
  console.log('Spring');
} else if (month >= 6 && month <= 8) {
  console.log('Summer');  // Output: Summer
} else if (month >= 9 && month <= 11) {
  console.log('Autumn');
} else {
  console.log('Winter');
}

Here we used the if-else control statement because we needed to compare the value of number which would not have been possible in switch

Summary

Now that we have learnt the three pillars of control flow in javascript. Here is a quick recap:

  • if — Run a block of code only when a condition is true

  • if-else — Choose between two paths: one for true, one for false

  • else if — Chain multiple conditions to handle many possible outcomes

  • switch — Match one value against many exact cases — cleaner than long if-else chains

  • break — Always use inside switch cases to prevent fall-through bugs

  • default — The fallback when no switch case matches (like else)

Statement

Purpose

Key Syntax

Best For

if

Run code if condition is true

if (x > 5) { ... }

Simple single conditions

if-else

Choose between two paths

if (...) { } else { }

True/false decisions

else if

Multiple conditions in sequence

if ... else if ... else

Range checks, grades, scores

switch

Match one value to many cases

switch(x) { case 1: ... }

Menu items, days, categories

Conclusion

Control flow is something we will use in all the Javascript program we ever will write. Once we get comfortable with these statements, we will able to write code that responded to the use input, validates data, and make smart decisions on its own.