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

Search for a command to run...

No comments yet. Be the first to comment.
Realtime Systems Deep Dive: Polling, WebSockets, SSE, and Pub/Sub Explained TL;DR: Realtime communication is not one technology β it's a spectrum of patterns, each with distinct trade-offs in latency

Realtime Systems Deep Dive: Polling, WebSockets, SSE, and Pub/Sub Explained TL;DR: Realtime communication is not one technology β it's a spectrum of patterns, each with distinct trade-offs in latency

How ChatGPT Understands Your Questions: A Deep Dive into LLMs, Tokenization, and Transformers TL;DR: ChatGPT doesn't "read" your question the way you do. It converts text into numbers, processes thos

Building Scalable Systems: Caching, Rate Limiting, and Observability TL;DR: Scaling isn't just about adding more servers. It's about protecting your system with intelligent caching, guarding your API

Kafka Explained Like You're 5: Events, Partitions, and Consumer Groups TL;DR: Kafka is a distributed event streaming platform that decouples producers from consumers using topics and partitions, enab

By Saurabh Prajapati β Full-Stack Engineer @ IBM India | GenAI & React Enthusiast
Let me be honest. When I first saw the term "control flow" in a programming book, I thought it sounded way more complicated than it actually is.
Here's the simple truth: control flow just means the order in which your code runs.
By default, JavaScript reads your code from top to bottom, line by line. But what if you only want certain code to run in certain situations? That's exactly where control flow comes in.
Think about real life for a second:
π¦ If the traffic light is green β you drive. Otherwise β you stop.
That's control flow. You're making a decision based on a condition.
In JavaScript, we do the same thing. We check a condition, and based on whether it's true or false, we run different pieces of code.
Let's explore exactly how that works.
if StatementThe if statement is the most basic building block of decision-making in JavaScript.
if (condition) {
// code runs only if condition is true
}
let age = 20;
if (age >= 18) {
console.log("You are eligible to vote!");
}
Output: You are eligible to vote!
The code inside the curly braces {} only runs if the condition age >= 18 is true.
If age was 15, nothing would happen at all. The block would be completely skipped.
π‘ I wish I knew this earlier: The condition inside
if()doesn't have to be a comparison. Anything "truthy" works β like a non-empty string, a number that isn't zero, or even an object. JavaScript is flexible like that.
if-else StatementOkay, but what if you want something to happen even when the condition is false? That's where else comes in.
if (condition) {
// runs if condition is true
} else {
// runs if condition is false
}
let marks = 35;
if (marks >= 40) {
console.log("You passed!");
} else {
console.log("You failed. Better luck next time.");
}
Output: You failed. Better luck next time.
Think of if-else like a fork in the road. You always take one path or the other β never both, never neither.
[Condition?]
|
YES β run if block
|
NO β run else block
This is the most common pattern you'll use as a developer. I use it literally every day at work.
else if LadderSometimes two options aren't enough. What if you have three or more conditions to check?
That's where else if steps in.
if (condition1) {
// runs if condition1 is true
} else if (condition2) {
// runs if condition2 is true
} else {
// runs if none of the above are true
}
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 retry");
}
Output: Grade: C
JavaScript checks each condition from top to bottom. The moment it finds one that's true, it runs that block and stops checking the rest.
This is important! Here's what I mean:
let marks = 95;
if (marks >= 60) {
console.log("Grade: C"); // β This runs first... and stops!
} else if (marks >= 90) {
console.log("Grade: A"); // β This never runs!
}
See the bug? Order matters. Always put your most specific or highest condition first.
π I made this exact mistake when I was learning. Spent 20 minutes debugging a grading script before realizing the conditions were in the wrong order. Lesson learned.
βββββββββββββββββββ
β Start β
ββββββββββ¬βββββββββ
β
ββββββββββΌβββββββββ
β Check β
β Condition 1? β
ββββββββββ¬βββββββββ
YES β NO
βββββββββββββ βββββββββββββ
βΌ βΌ
βββββββββββ ββββββββββββββββββ
β Run β β Check β
β Block 1 β β Condition 2? β
βββββββββββ ββββββββββ¬ββββββββ
YES β NO
βββββββββββββ ββββββββββββ
βΌ βΌ
βββββββββββ βββββββββββββββ
β Run β β Run else β
β Block 2 β β block β
βββββββββββ βββββββββββββββ
switch StatementNow here's something I found really interesting when I first discovered it.
Imagine you're building a day-of-the-week app. With if-else, it would look like this:
if (day === 1) {
console.log("Monday");
} else if (day === 2) {
console.log("Tuesday");
} else if (day === 3) {
console.log("Wednesday");
// ...and so on
That's a lot of repetition. switch is designed exactly for situations like this β when you're comparing one variable against many fixed values.
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code if no case matches
}
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
break Doing Here?Great question. I was confused about this too at first.
Without break, JavaScript doesn't stop after finding a matching case. It keeps running every case below it β which is almost never what you want.
This behavior is called "fall-through".
let day = 3;
switch (day) {
case 3:
console.log("Wednesday"); // β This runs
case 4:
console.log("Thursday"); // β This ALSO runs (no break!)
case 5:
console.log("Friday"); // β And this too!
}
Output:
Wednesday
Thursday
Friday
See the problem? We matched case 3, but without break, it kept going.
Always add
breakat the end of each case. (Unless you intentionally want fall-through β which is rare, but possible for grouping cases.)
let day = 6;
switch (day) {
case 6:
case 7:
console.log("It's the weekend! π");
break;
default:
console.log("It's a weekday.");
}
Output: It's the weekend! π
Here both case 6 and case 7 fall through to the same code block. This is a clean pattern for grouping similar cases.
default?default is like the else in a switch. It runs when no case matches.
let color = "purple";
switch (color) {
case "red":
console.log("Red");
break;
case "blue":
console.log("Blue");
break;
default:
console.log("Unknown color"); // β This runs
}
ββββββββββββββββββββ
β switch(value) β
ββββββββββ¬ββββββββββ
β
ββββββββββββΌβββββββββββ
βΌ βΌ βΌ
[case 1] [case 2] [default]
β β β
(code) (code) (code)
β β β
[break] [break] (end)
switch vs if-else?This is the question I kept asking myself. Here's what I've figured out after using both in real projects:
| Situation | Use This |
|---|---|
| Checking a range (e.g., marks > 80) | if-else |
| Comparing one value to many fixed options | switch |
Complex conditions with && or ` |
|
| Menu selection, day/month names, status codes | switch |
| Two or three simple options | if-else |
| Five or more fixed values | switch |
Use
if-elsewhen you need flexible conditions. Useswitchwhen you're matching one thing to many exact values.
Here's what genuinely surprised me while diving into this topic:
1. switch uses strict equality (===) It doesn't do type conversion. So case "1" won't match if your value is the number 1.
let input = 1; // number
switch (input) {
case "1": // β string "1" β won't match!
console.log("One");
break;
case 1: // β number 1 β matches!
console.log("One (number)");
break;
}
2. You can use switch with strings too
let language = "JavaScript";
switch (language) {
case "JavaScript":
console.log("Runs in the browser!");
break;
case "Python":
console.log("Great for data science!");
break;
default:
console.log("Cool choice!");
}
3. if conditions can be anything truthy
let name = "Saurabh";
if (name) {
console.log("Name exists: " + name);
}
// Works! Because a non-empty string is truthy.
Control flow is one of those foundational concepts that everything else in programming is built on. Once you understand how if, else, and switch work, you start seeing them everywhere.
Here's a quick recap of what we covered:
if β runs code when a condition is true
if-else β runs one block if true, another if false
else if β chains multiple conditions together
switch β cleanly matches one value against many fixed options
break β essential in switch to prevent fall-through
default β the fallback when no case matches
Saurabh Prajapati (SP) Full-Stack Software Engineer at IBM India Software Lab, working on cloud-native enterprise solutions with Maximo. Passionate about GenAI, React, and modern web technologies.
Skills: JavaScript Β· TypeScript Β· React Β· Next.js Β· Node.js Β· LangChain Β· OpenAI API Β· AWS Β· Docker
π§ saurabhprajapati120@gmail.com π GitHub: prajapatisaurabh πΌ LinkedIn: saurabh-prajapati