Control Flow in JavaScript
What Is Control Flow?
Control flow is the order in which statements are executed in a program. Without control flow, a program runs only linearly from top to bottom. Control flow allows a program to:
- Choose an execution path based on a condition (branching)
- Repeat execution multiple times (looping)
- Exit a loop or switch
1. if...else (Conditional Statements)
if...else is used to execute a block of code based on a condition.
// Basic if...else
let gpa = 3.75;
if (gpa >= 3.5) {
console.log("Cum Laude!");
} else if (gpa >= 3.0) {
console.log("Very Satisfactory!");
} else if (gpa >= 2.5) {
console.log("Satisfactory!");
} else if (gpa >= 2.0) {
console.log("Fair!");
} else {
console.log("Poor!");
}
// Output: "Cum Laude!"
Complete Example in an Academic Portal
// Determine student status based on GPA
function determineStatus(gpa, completedCredits, totalCredits) {
let status;
let description;
if (gpa === null || gpa === undefined) {
status = "No data yet";
description = "GPA not available yet";
} else if (gpa >= 3.5 && completedCredits >= totalCredits * 0.75) {
status = "Graduated with Honors";
description = "Top graduate candidate";
} else if (gpa >= 2.0 && completedCredits >= totalCredits * 0.5) {
status = "Active";
description = "Active student";
} else if (gpa >= 2.0) {
status = "Active";
description = "Needs to catch up on graduation credits";
} else if (gpa >= 1.0) {
status = "Academic Suspension";
description = "GPA below the minimum threshold";
} else {
status = "DO (Drop Out)";
description = "Does not meet academic requirements";
}
return { status, description };
}
// Usage
const student1 = determineStatus(3.75, 120, 144);
console.log(`${student1.status} — ${student1.description}`);
// "Graduated with Honors — Top graduate candidate"
const student2 = determineStatus(1.5, 30, 144);
console.log(`${student2.status} — ${student2.description}`);
// "Academic Suspension — GPA below the minimum threshold"
2. switch
switch is best used when comparing one variable against many values.
// Basic switch
let day = new Date().getDay(); // 0-6 (Sunday-Saturday
let dayName;
switch (day) {
case 0: dayName = "Sunday"; break;
case 1: dayName = "Monday"; break;
case 2: dayName = "Tuesday"; break;
case 3: dayName = "Wednesday"; break;
case 4: dayName = "Thursday"; break;
case 5: dayName = "Friday"; break;
case 6: dayName = "Saturday"; break;
default: dayName = "Invalid";
}
console.log(`Today is: ${dayName}`);
Switch with Strings
// Switch to determine the class schedule
function getSchedule(code) {
let schedule;
switch (code) {
case "IF101":
schedule = {
course: "Web Programming",
day: "Monday",
time: "08:00-10:30",
room: "Computer Lab 3"
};
break;
case "IF102":
schedule = {
course: "Database",
day: "Tuesday",
time: "10:30-13:00",
room: "Computer Lab 2"
};
break;
case "IF103":
schedule = {
course: "Algorithms",
day: "Wednesday",
time: "08:00-10:30",
room: "Classroom 101"
};
break;
default:
schedule = { error: "Invalid course code" };
}
return schedule;
}
console.log(getSchedule("IF101"));
// { course: "Web Programming", day: "Monday", ... }
Switch Without Break (Fall-through)
// Fall-through: several cases share the same code
function getGpaCategory(gpa) {
let category;
switch (true) {
case gpa >= 3.5:
category = "A (Cum Laude)";
break;
case gpa >= 3.0:
category = "B (Very Satisfactory)";
break;
case gpa >= 2.5:
category = "C (Satisfactory)";
break;
case gpa >= 2.0:
category = "D (Fair)";
break;
case gpa >= 0:
category = "E (Poor)";
break;
default:
category = "Invalid";
}
return category;
}
console.log(getGpaCategory(3.75)); // "A (Cum Laude)"
console.log(getGpaCategory(2.25)); // "D (Fair)"
3. Loops
for Loop
Most commonly used for iteration with a known count.
// Basic for loop
for (let i = 0; i < 5; i++) {
console.log(`Iteration ${i}`);
}
// Iterating over an array
const courseList = [
"Web Programming",
"Database",
"Algorithms",
"Computer Networks",
"English"
];
for (let i = 0; i < courseList.length; i++) {
console.log(`${i + 1}. ${courseList[i]}`);
}
// Output:
// 1. Web Programming
// 2. Database
// 3. Algorithms
// ...
while Loop
Repeats as long as the condition is still true.
// Basic while loop
let counter = 0;
while (counter < 5) {
console.log(`Counter: ${counter}`);
counter++;
}
// while in an academic portal: checking course capacity
let capacity = 3;
let applicants = 0;
while (capacity > 0 && applicants < 5) {
applicants++;
capacity--;
console.log(`Applicant #${applicants}. Remaining capacity: ${capacity}`);
}
if (capacity === 0) {
console.log("Capacity full!");
} else if (applicants === 5) {
console.log("All applicants have been processed.");
}
do...while Loop
Similar to while, but guaranteed to run at least once.
// Basic do...while
let input;
do {
input = prompt("Enter your student ID (10 digits):");
} while (input.length !== 10);
// do...while in an academic portal
let choice;
do {
console.log("\n=== MAIN MENU ===");
console.log("1. View Schedule");
console.log("2. Enroll in a Course");
console.log("3. View Grades");
console.log("4. Exit");
// Simulated input
choice = "4"; // In reality, this comes from prompt/input
console.log(`Choice: ${choice}`);
switch (choice) {
case "1": console.log("Displaying schedule..."); break;
case "2": console.log("Processing course enrollment..."); break;
case "3": console.log("Displaying grades..."); break;
case "4": console.log("Thank you!"); break;
default: console.log("Invalid choice!");
}
} while (choice !== "4");
for...in Loop
Iterates over the property keys of an object.
// for...in for an object
const student = {
studentId: "2024100123",
name: "John Smith",
major: "Computer Science",
semester: 3,
gpa: 3.75
};
for (let key in student) {
console.log(`${key}: ${student[key]}`);
}
// Output:
// studentId: 2024100123
// name: John Smith
// major: Computer Science
// semester: 3
// gpa: 3.75
// ⚠️ Avoid for...in for arrays (use for...of instead)
// for...in iterates over all enumerable properties, including the prototype
for...of Loop (ES6)
Iterates over the values of an iterable (array, string, Map, Set).
// for...of for an array
const scores = [85, 90, 78, 92, 88];
for (let score of scores) {
console.log(`Score: ${score}`);
}
// for...of for a string
const name = "John";
for (let char of name) {
console.log(char); // B, u, d, i
}
// for...of for an array of objects
const studentList = [
{ studentId: "2024100123", name: "John", gpa: 3.75 },
{ studentId: "2024100124", name: "Mike", gpa: 3.50 },
{ studentId: "2024100125", name: "Anna", gpa: 3.90 }
];
for (let m of studentList) {
console.log(`${m.name} — GPA: ${m.gpa}`);
}
// for...of with entries() to get the index
const days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
for (let [index, day] of days.entries()) {
console.log(`${index + 1}. ${day}`);
}
4. break and continue
break
Forces exit from a loop or switch.
// break in a for loop
for (let i = 0; i < 10; i++) {
if (i === 5) break; // Stop when i === 5
console.log(i);
}
// Output: 0, 1, 2, 3, 4
// break in a while loop
let number = 0;
while (true) {
if (number > 10) break; // Infinite loop, stops at > 10
console.log(number);
number++;
}
// break in nested loops
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) break; // Only exits the inner loop
console.log(`i=${i}, j=${j}`);
}
}
// Output: i=0,j=0 i=0,j=1 i=0,j=2 i=1,j=0 i=2,j=0 i=2,j=1 i=2,j=2
continue
Skips the current iteration and moves on to the next one.
// continue in a for loop
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) continue; // Skip even numbers
console.log(i);
}
// Output: 1, 3, 5, 7, 9
// continue in an academic portal: filter courses that have not been taken
const allCourses = [
"Web Programming",
"Database",
"Algorithms",
"Computer Networks",
"English"
];
const alreadyTaken = ["Web Programming", "Algorithms"];
for (let course of allCourses) {
if (alreadyTaken.includes(course)) continue;
console.log(`Can be taken: ${course}`);
}
// Output:
// Can be taken: Database
// Can be taken: Computer Networks
// Can be taken: English
Case Study: Determining Student Status
// === STUDENT STATUS DETERMINATION SYSTEM ===
const studentList = [
{ studentId: "2024100123", name: "John Smith", gpa: 3.75, completedCredits: 120, totalCredits: 144 },
{ studentId: "2024100124", name: "Mike Brown", gpa: 2.80, completedCredits: 80, totalCredits: 144 },
{ studentId: "2024100125", name: "Anna Green", gpa: 1.75, completedCredits: 45, totalCredits: 144 },
{ studentId: "2024100126", name: "Dana Lestari", gpa: 3.20, completedCredits: 100, totalCredits: 144 },
{ studentId: "2024100127", name: "Eric Putra", gpa: 0.80, completedCredits: 20, totalCredits: 144 }
];
function determineStatus(student) {
const { gpa, completedCredits, totalCredits } = student;
let status, description, warning = null;
// Check for null/undefined GPA
if (gpa == null) {
status = "NO DATA";
description = "GPA not available yet";
}
// Check graduation with honors
else if (gpa >= 3.5 && (completedCredits / totalCredits) >= 0.75) {
status = "GRADUATED CUM LAUDE";
description = `GPA ${gpa} — Top graduate candidate!`;
}
// Check graduation
else if (gpa >= 2.0 && completedCredits >= totalCredits) {
status = "GRADUATED";
description = `GPA ${gpa} — Meets graduation requirements`;
}
// Check active status
else if (gpa >= 2.0) {
status = "ACTIVE";
description = `GPA ${gpa} — Progress: ${Math.round((completedCredits / totalCredits) * 100)}%`;
}
// Check academic suspension
else if (gpa >= 1.0) {
status = "ACADEMIC SUSPENSION";
description = `GPA ${gpa} — Below the minimum threshold (2.0)`;
warning = "Contact your academic advisor!";
}
// DO
else {
status = "DROP OUT";
description = `GPA ${gpa} — Does not meet academic requirements`;
warning = "Drop-out administrative process required";
}
return { ...student, status, description, warning };
}
// Process all students
console.log("=== STUDENT STATUS REPORT ===\n");
for (let m of studentList) {
const result = determineStatus(m);
console.log(`Student ID: ${result.studentId}`);
console.log(`Name: ${result.name}`);
console.log(`Status: ${result.status}`);
console.log(`Description: ${result.description}`);
if (result.warning) {
console.log(`⚠️ Warning: ${result.warning}`);
}
console.log("---");
}
// Calculate statistics
let active = 0, suspended = 0, graduated = 0, doCount = 0;
for (let m of studentList) {
const result = determineStatus(m);
if (result.status.includes("ACTIVE")) active++;
else if (result.status.includes("SUSPENSION")) suspended++;
else if (result.status.includes("GRADUATED")) graduated++;
else if (result.status.includes("DROP")) doCount++;
}
console.log("\n=== STATISTICS ===");
console.log(`Active: ${active}`);
console.log(`Academic Suspension: ${suspended}`);
console.log(`Graduated: ${graduated}`);
console.log(`Drop Out: ${doCount}`);
Summary
| Construct | Function | Use When |
|---|---|---|
if...else |
Conditional branching | Complex conditions, ranges |
switch |
Branching by value | Many possible values |
for |
Bounded iteration | Known iteration count |
while |
Condition-based iteration | Unknown iteration count |
do...while |
Iterate at least once | Input validation |
for...in |
Iterate object keys | Object properties |
for...of |
Iterate iterable values | Arrays, strings, Map, Set |
break |
Exit a loop | Completion condition found |
continue |
Skip the current iteration | Filtering specific items |