JavaScript Control Flow: Teaching Our Code to Decide
What is Control Flow?
By default, JavaScript reads code from top to bottom. However, in the real world, we make decisions based on conditions: If it is raining, I take an umbrella; else, I don't. Control Flow allows our program to skip or execute specific blocks of code based on these types of logic.
In this article, we’ll learn how control flow works using common statements in JavaScript such as:
ifif-elseelse ifswitch
The
ifandif-elseStatements
The if statement is the most basic form of control. If the condition inside the parentheses is true, the code inside the curly braces runs.
Syntax :
if (condition) {
// code runs if condition is true
}
But sometimes we want two possible outcomes.
Example:
Pass or fail
Access granted or denied
In this case, we use if-else statement.
Syntax :
if (condition) {
// runs if true
} else {
// runs if false
}
Example :
let age = 20;
if (age >= 18) {
console.log("You are eligible to vote.");
} else {
console.log("You are too young to vote.");
}
The
else ifLadder
When we have more than two possible outcomes, we use an else if ladder. This allows us to check multiple conditions in sequence
Syntax :
if (condition1) {
// code
} else if (condition2) {
// code
} else if (condition3) {
// code
} else {
// default code
}
Example :
let marks = 85;
if (marks >= 90) {
console.log("Grade: A+");
} else if (marks >= 80) {
console.log("Grade: A");
} else if (marks >= 70) {
console.log("Grade: B");
} else {
console.log("Grade: F");
}
The
switchStatement
The switch statement is a cleaner way to handle multiple "equal to" checks. Instead of writing many else if statements, we define "cases."
Syntax :
switch (value) {
case option1:
// code
break;
case option2:
// code
break;
default:
// code
}
Example :
let dayNumber = 3;
let dayName;
switch (dayNumber) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default:
dayName = "Invalid Day";
}
console.log(dayName); // Output: Wednesday
Why break is Important
Inside a switch statement, the break keyword stops execution after a match is found.
Without break, the program continues running the next cases.
Example without break:
let day = 1;
switch (day) {
case 1:
console.log("Monday");
case 2:
console.log("Tuesday");
}
Output:
Monday
Tuesday
Because there was no break, the execution continued.
So in most cases, we should always include break after each case.
When to Use switch vs if-else
Use
if-elsewhen:We have complex logical conditions (e.g.,
marks > 80 && marks < 90).We are checking ranges of values.
Use
switchwhen:We are comparing a single variable against many specific, fixed values (e.g., a menu system or days of the week).
We want better readability for long lists of "equals" checks.
