Control Flow in JavaScript: Making Your Code Think

In programming, control flow is the order in which individual statements, instructions, or function calls are executed. By default, JavaScript reads code from top to bottom. However, life isn't a straight line, and neither is coding. Control flow allows us to skip sections of code, repeat them, or choose between different paths.
Think of it like a morning routine:
If it is raining, take an umbrella.
Else, just wear a jacket.
- The
ifStatement
The if statement is the most basic control structure. It executes a block of code only if a specified condition is true.
let age = 18;
if (age >= 18) {
console.log("You are eligible to vote!");
}
- The
if-elsestatement
Sometimes you want to do one thing if a condition is true and another thing if it's false. That’s where else comes in.
let marks = 45;
if (marks >= 50) {
console.log("Result: Pass");
} else {
console.log("Result: Fail");
}
- The
else-ifladder
When you have multiple conditions to check, you can chain them together. JavaScript will check them one by one until it finds a true one.
let temperature = 25;
if (temperature > 30) {
console.log("It's a hot day.");
} else if (temperature > 20) {
console.log("The weather is pleasant.");
} else {
console.log("It's a bit chilly.");
}
- The
switchstatement
The switch statement is a more organized way to handle multiple discrete values for a single variable. It’s like a specialized "lookup table" for your code.
The Importance of Break
Without a break statement, JavaScript will continue executing the code in the subsequent cases even if the condition doesn't match–this is called "falling through." Always use break to exit the switch once a match is found.
let fruit = "Apple";
switch (fruit) {
case "Banana":
console.log("Bananas are $1.00");
break;
case "Apple":
console.log("Apples are $2.00");
break;
default:
console.log("Fruit not found.");
}
When to use switch vs. if-else?
| Feature | if-else | switch |
|---|---|---|
| Conditions | Best for ranges (e.g., age > 18) or complex logic. |
Best for fixed, discrete values (e.g., day == 1). |
| Readability | Can get messy with too many "ladders." | Very clean and readable for many cases. |
| Performance | Slightly slower for many conditions. | Can be faster as it uses a branch table. |

