Control Flow Examples in JavaScript
Control flow determines the order in which statements and expressions are executed. Let's look at some real-world examples using if
, switch
, for
, while
, and break/continue
.
✅ Example 1: Login Access Check
let isLoggedIn = true;
if (isLoggedIn) {
console.log("Welcome back!");
} else {
console.log("Please log in.");
}
✅ Example 2: Grade Evaluation
let marks = 85;
if (marks >= 90) {
console.log("Grade: A");
} else if (marks >= 75) {
console.log("Grade: B");
} else {
console.log("Grade: C");
}
✅ Example 3: Day of the Week using Switch
let day = "Saturday";
switch (day) {
case "Monday":
console.log("Work day");
break;
case "Saturday":
case "Sunday":
console.log("Weekend!");
break;
default:
console.log("Just another day");
}
✅ Example 4: Loop with Continue
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skip 3
}
console.log(i);
}
✅ Example 5: Loop with Break
let count = 0;
while (true) {
count++;
if (count === 4) {
break;
}
console.log("Counting:", count);
}
🎯 Summary
- Use if/else for binary decisions
- Use switch when checking one value against many
- Use loops for repetition
- Use break to exit early
- Use continue to skip current iteration
✅ Practice these patterns to master control flow logic in JavaScript!