Control Flow in JavaScript: If, Else, and Switch Explained
Every program you've ever used makes decisions. Your music app skips explicit songs when parental controls are on. Your bank app blocks a transaction if your balance is too low. Your favorite game says "Game Over" when your health hits zero. All of this happens because of control flow โ and in this post, you'll learn exactly how it works in JavaScript.
1. What Is Control Flow?
Imagine you're getting ready in the morning. You don't just blindly follow the same routine every day โ you make decisions:
If it's raining, grab an umbrella.
Otherwise, leave it at home.
If you're running late, skip breakfast.
This is exactly what control flow means in programming. By default, JavaScript reads and executes your code line by line, top to bottom. But with control flow statements, you can tell JavaScript:
"Don't just run everything blindly โ check a condition first, then decide what to do."
Control flow lets your program branch into different paths based on conditions. The three main tools for this in JavaScript are:
ifstatementsif-elseandelse ifladdersswitchstatements
Let's explore each one.
2. The if Statement
The if statement is the simplest form of decision-making. It says: "Only run this block of code IF the condition is true."
Syntax
js
if (condition) {
// code to run if condition is true
}
If the condition is false, JavaScript simply skips the block entirely and moves on.
Real-Life Example: Checking Age for Voting
let age = 20;
if (age >= 18) {
console.log("You are eligible to vote.");
}
// Output: You are eligible to vote.
Step-by-step walkthrough:
JavaScript reads
age >= 18It checks: is
20 >= 18? โ Yes, trueSo it enters the block and prints the message
Now try with a different value:
let age = 15;
if (age >= 18) {
console.log("You are eligible to vote.");
}
// No output โ the block is skipped
Since 15 >= 18 is false, JavaScript quietly skips the entire if block. Nothing happens.
Key Takeaway
Use
ifwhen you only care about what happens when the condition is true, and want to do nothing otherwise.
3. The if-else Statement
What if you want to handle both cases โ when the condition is true and when it's false? That's where else comes in.
Syntax
js
if (condition) {
// runs if condition is true
} else {
// runs if condition is false
}
Real-Life Example: Pass or Fail
js
let marks = 45;
if (marks >= 50) {
console.log("Result: Pass โ
");
} else {
console.log("Result: Fail โ");
}
// Output: Result: Fail โ
Step-by-step walkthrough:
JavaScript checks: is
45 >= 50? โ No, falseIt skips the
ifblockIt falls into the
elseblock and prints"Result: Fail โ"
Only one of the two blocks will ever run โ never both.
Another Example: Even or Odd
js
let number = 7;
if (number % 2 === 0) {
console.log(number + " is Even");
} else {
console.log(number + " is Odd");
}
// Output: 7 is Odd
The % operator gives the remainder after division. 7 % 2 gives 1, which is not 0, so the else block runs.
Key Takeaway
Use
if-elsewhen there are exactly two possible outcomes โ the condition is either true or false.
4. The else if Ladder
Real life rarely gives us just two choices. What if you need to check multiple conditions in sequence? That's where else if comes in โ it lets you build a ladder of conditions.
Syntax
js
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 are true
}
JavaScript checks each condition from top to bottom and stops as soon as it finds one that's true.
Real-Life Example: Grade Calculator
js
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");
} else if (marks >= 40) {
console.log("Grade: D");
} else {
console.log("Grade: F โ Please retake the exam");
}
// Output: Grade: C
Step-by-step walkthrough:
Is
72 >= 90? โ No. Move on.Is
72 >= 75? โ No. Move on.Is
72 >= 60? โ Yes! โ Print"Grade: C"and stop.
JavaScript never even checks the >= 40 condition because it already found a match.
Real-Life Example: Time of Day Greeting
js
let hour = 14; // 2 PM in 24-hour format
if (hour < 12) {
console.log("Good Morning! โ๏ธ");
} else if (hour < 17) {
console.log("Good Afternoon! ๐ค๏ธ");
} else if (hour < 21) {
console.log("Good Evening! ๐");
} else {
console.log("Good Night! ๐");
}
// Output: Good Afternoon! ๐ค๏ธ
Key Takeaway
Use
else ifwhen you have 3 or more possible outcomes that depend on a single variable being checked against different ranges or values.
5. The switch Statement
The switch statement is a cleaner alternative when you're comparing one variable against many specific values. Instead of writing a long chain of else if, switch lays all the options out neatly.
Syntax
js
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 matches
}
Real-Life Example: Day of the Week
js
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 number");
}
// Output: Wednesday
Step-by-step walkthrough:
JavaScript evaluates
dayโ it's3It checks
case 1โ not a matchIt checks
case 2โ not a matchIt checks
case 3โ match! โ prints"Wednesday"It hits
breakโ exits the switch block immediately
๐ด Understanding break โ This Is Critical
The break keyword tells JavaScript: "You're done. Exit the switch now."
What happens if you forget it? JavaScript will fall through โ it keeps running every case below the matched one, even if they don't match. This is called fallthrough behavior and is a common source of bugs.
let day = 3;
switch (day) {
case 3:
console.log("Wednesday");
// โ ๏ธ No break here!
case 4:
console.log("Thursday");
// โ ๏ธ No break here!
case 5:
console.log("Friday");
break;
}
// Output:
// Wednesday
// Thursday
// Friday
Even though day is 3, all three cases ran because there was no break to stop the flow. Always add break unless you deliberately want fallthrough.
Using Fallthrough Intentionally
Sometimes fallthrough is actually useful โ when multiple cases should share the same outcome:
js
let day = "Saturday";
switch (day) {
case "Saturday":
case "Sunday":
console.log("It's the weekend! ๐");
break;
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
console.log("It's a weekday. ๐ผ");
break;
default:
console.log("Unknown day");
}
// Output: It's the weekend! ๐
Here, both "Saturday" and "Sunday" fall through to the same console.log โ this is clean, intentional, and readable.
The default Case
default is like the else in an if-else โ it runs when no case matches. It's optional, but always a good idea to include it.
js
let trafficLight = "purple";
switch (trafficLight) {
case "red":
console.log("Stop ๐ด");
break;
case "yellow":
console.log("Slow down ๐ก");
break;
case "green":
console.log("Go! ๐ข");
break;
default:
console.log("Unknown signal โ proceed with caution");
}
// Output: Unknown signal โ proceed with caution
Key Takeaway
Use
switchwhen you're matching one variable against multiple exact values, and each case has a distinct action. Always usebreakunless you intentionally want fallthrough.
6. When to Use switch vs if-else
This is one of the most common questions beginners ask. Here's a clear breakdown:
| Scenario | Best Choice |
|---|---|
Checking a range of values (>= 60, < 100) |
if-else |
Checking complex conditions (age > 18 && hasID) |
if-else |
| Matching one variable to many exact values | switch |
| Two possible outcomes | if-else |
| Many named cases (days, months, menu options) | switch |
| Conditions involve different variables | if-else |
Side-by-Side Comparison
Here's the same logic written both ways โ you decide which is cleaner:
Using if-else:
js
let fruit = "mango";
if (fruit === "apple") {
console.log("๐ Apple selected");
} else if (fruit === "banana") {
console.log("๐ Banana selected");
} else if (fruit === "mango") {
console.log("๐ฅญ Mango selected");
} else {
console.log("Unknown fruit");
}
Using switch:
js
let fruit = "mango";
switch (fruit) {
case "apple":
console.log("๐ Apple selected");
break;
case "banana":
console.log("๐ Banana selected");
break;
case "mango":
console.log("๐ฅญ Mango selected");
break;
default:
console.log("Unknown fruit");
}
Both produce the same output. But when you have 10+ specific values to check, switch wins on readability every time.
The Golden Rule
If your conditions involve ranges, inequalities, or multiple variables โ use
if-elseIf you're matching one thing to a list of exact values โ use
switch
Putting It All Together
Here's a mini program that uses everything you've learned:
js
let studentMarks = 68;
let studentAge = 17;
// Check eligibility
if (studentAge < 5) {
console.log("Too young for school.");
} else if (studentAge < 18) {
console.log("School-going student.");
} else {
console.log("Adult learner.");
}
// Assign grade using switch
let grade;
if (studentMarks >= 90) {
grade = "A";
} else if (studentMarks >= 75) {
grade = "B";
} else if (studentMarks >= 60) {
grade = "C";
} else {
grade = "F";
}
switch (grade) {
case "A":
console.log("Outstanding performance! ๐");
break;
case "B":
console.log("Great job! Keep it up. ๐");
break;
case "C":
console.log("Good effort. Room to improve. ๐");
break;
default:
console.log("Needs significant improvement. ๐");
}
// Output:
// School-going student.
// Good effort. Room to improve. ๐
Summary
Here's everything you covered in one quick reference:
| Statement | Purpose |
|---|---|
if |
Run code only when condition is true |
if-else |
Handle true/false โ two outcomes |
else if |
Handle multiple conditions in order |
switch |
Match one value against many exact cases |
break |
Exit the switch block after a match |
default |
Fallback if no case matches |



