Control Flow in JavaScript
Introduction
Control flow in programming determines the order in which statements are executed. Normally, code runs from top to bottom, but control flow statements allow the program to make decisions and execute different blocks of code based on conditions.
In JavaScript, common control flow statements include:
ifif-elseelse ifswitch
1. What Control Flow Means in Programming
Control flow refers to how a program chooses which instructions to execute depending on conditions.
Real-Life Example
If it is raining → take an umbrella
Else → go outside normally.
Programming follows the same logic.
Example in JavaScript:
let isRaining = true;
if (isRaining) {
console.log("Take an umbrella");
}
2. The if Statement
The if statement executes a block of code only when the condition is true.
Syntax
if(condition){
// code to run
}
Example
let age = 18;
if(age >= 18){
console.log("You are eligible to vote");
}
If the condition is true, the message will be displayed.
3. The if-else Statement
The if-else statement allows the program to choose between two possible actions.
Syntax
if(condition){
// code if true
}else{
// code if false
}
Example
let age = 16;
if(age >= 18){
console.log("You can vote");
}else{
console.log("You cannot vote yet");
}
4. The else if Ladder
The else if ladder is used when multiple conditions need to be checked.
Syntax
if(condition1){
// code
}
else if(condition2){
// code
}
else{
// default code
}
Example (Marks Grading)
let marks = 75;
if(marks >= 90){
console.log("Grade A");
}
else if(marks >= 70){
console.log("Grade B");
}
else if(marks >= 50){
console.log("Grade C");
}
else{
console.log("Fail");
}
5. The switch Statement
The switch statement is used when a variable can have multiple specific values.
Syntax
switch(expression){
case value1:
// code
break;
case value2:
// code
break;
default:
// default code
}
Example
let day = 3;
switch(day){
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Invalid day");
}
Role of break
The break statement stops the execution of the switch block.
Without break, the program continues to the next case.
6. When to Use switch vs if-else
| Feature | if-else | switch |
|---|---|---|
| Best for | Complex conditions | Fixed values |
| Conditions | Range conditions | Exact matches |
| Readability | Good for logic checks | Cleaner for many cases |
Example
Use if-else for marks or age comparisons:
if(age > 18)
Use switch for menu or day selection:
switch(day)
Conclusion
Control flow statements allow programs to make decisions and execute different instructions based on conditions.
Using statements like if, if-else, else-if, and switch, developers can create flexible and logical programs.