Understanding Control Flow in JavaScript
Control flow in JavaScript determines the direction in which the code executes. By default, JavaScript runs code from top to bottom, but using control structures like if
, else
, and switch
, we can change this flow based on certain conditions.
if Statement
The if
statement evaluates a condition. If it's true, it runs the associated block of code.
let age = 20;
if (age >= 18) {
console.log("You are eligible to vote.");
}
Output:
You are eligible to vote.
Q: What happens if the condition is false?
A: Nothing inside the if
block runs. Control moves to the next statement.
if...else Statement
Use else
to define an alternative block that runs if the condition is false.
let temperature = 10;
if (temperature > 20) {
console.log("It's warm outside.");
} else {
console.log("It's cold outside.");
}
Output:
It's cold outside.
else if Ladder
Use else if
to check multiple conditions in sequence. The first true condition will execute, and others will be skipped.
let score = 75;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
Output:
Grade: C
Q: What if more than one condition is true?
A: Only the first true condition is executed. Others are ignored.
switch Statement
The switch
statement is used when you want to compare one value against multiple possible matches.
let fruit = "apple";
switch (fruit) {
case "banana":
console.log("You chose banana.");
break;
case "apple":
console.log("You chose apple.");
break;
case "mango":
console.log("You chose mango.");
break;
default:
console.log("Unknown fruit.");
}
Output:
You chose apple.
Why Use break in switch?
If you don't use break
, JavaScript continues to execute the next cases even if a match is found (this is called “fall-through”).
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the week");
case "Tuesday":
console.log("Second day");
break;
}
Output:
Start of the week Second day
Tip: Always use break
unless you intentionally want fall-through behavior.
Conclusion
- Use
if
andelse if
for range or boolean conditions. - Use
switch
for fixed values comparison (e.g., exact matches). - Never forget
break
in switch unless you need multiple cases to execute.