Flow Control Fundamentals
The execution order of code directly impacts program outcomes. Flow control mechanisms determine how statements are sequenced and repeated throughout a program. JavaScript provides three primary flow control structures: sequential, conditional, and repetitive structures. Understanding these structures is essential for building dynamic, responsive applications.
Sequential Execution
Sequential execution represents the simplest control flow pattern. Statements execute in the order they appear, from top to bottom, unless modified by conditional or loop structures. Most code follows this straightforward pattern.
Conditional Statements
Single Branch: if Statement
The if statement executes a block of code only when a specified condition evaluates to true.
let userAge = 25;
if (userAge >= 18) {
console.log("Access granted");
}
Dual Branch: if-else Statement
The if-else structure provides an alternative path when the condition is false.
let temperature = 30;
if (temperature > 25) {
console.log("It's hot outside");
} else {
console.log("Weather is comfortable");
}
Multiple Branches: if-else-if Statement
Chain multiple conditions to handle various scenarios.
let score = 85;
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");
}
Ternary Operator
The ternary operator provides a compact syntax for simple conditional assignments.
let age = 20;
let status = age >= 18 ? "adult" : "minor";
console.log(status);
Switch Statement
The switch statement evaluates an expression and matches it against multiple case values. It's particularly useful when comparing a variable against multiple discrete values.
let fruit = "apple";
switch (fruit) {
case "banana":
console.log("Yellow fruit");
break;
case "apple":
console.log("Red or green fruit");
break;
case "orange":
console.log("Citrus fruit");
break;
default:
console.log("Unknown fruit");
}
Choosing Between switch and if-else-if
| Scenario | Recommended Structure |
|---|---|
| Comparing against discrete values | switch |
| Range comparisons | if-else-if |
| Complex boolean conditions | if-else-if |
| Few branches | if-else-if (slightly faster) |
| Many branch | switch (more efficient) |
Loop Structures
Loops automate repetitive tasks by executing code blocks multiple times.
for Loop
The for loop repeats a block of code a specified number of times. It consists of an initializer, condition, and increment expression.
for (let i = 0; i < 5; i++) {
console.log(`Iteration number: ${i}`);
}
Debugging Techniques
Setting breakpoints in browser developer tools (F12 → Sources) allows inspection of variable values during execution. Use the Watch panel to monitor specific variables and F11 to step through code line by line. Debugging skill are invaluable for identifying and resolving issues efficiently.
Nested for Loops
Loops can contain other loops, enabling complex patterns like grids and triangles.
// Print a 5x5 grid
for (let row = 0; row < 5; row++) {
let line = "";
for (let col = 0; col < 5; col++) {
line += "* ";
}
console.log(line);
}
Key Points for Nested Loops
- The outer loop executes once, during which the inner loop completes all iterations
- Plan algorithm logic before writing code
- Break down complex patterns into simpler components
while Loop
The while loop continues executing as long as its condition remains true.
let counter = 0;
while (counter < 3) {
console.log(`Count: ${counter}`);
counter++;
}
Execution Flow:
- Evaluate the condition
- If true, execute the loop body
- Return to step 1
- Exit when condition becomes false
do-while Loop
The do-while loop guarantees at least one execution by checking the condition after running the loop body.
let number = 1;
do {
console.log(`Number is: ${number}`);
number++;
} while (number <= 5);
Comparison of Loop Types
| Loop Type | Condition Check | Minimum Executions |
|---|---|---|
| for | Before | 0 |
| while | Before | 0 |
| do-while | After | 1 |
Practical Guidance: for loops are preferred for counted iterations due to their concise syntax. while loops suit scenarios requiring flexible exit conditions, while do-while handles cases needing guaranteed initial execution.
Loop Control: continue and break
continue terminates the current iteration and proceeds to the next one.
for (let i = 0; i < 5; i++) {
if (i === 2) {
continue;
}
console.log(`Processing item: ${i}`);
}
// Output: 0, 1, 3, 4 (skips 2)
break immediately exits the enclosing loop entirely.
for (let i = 0; i < 10; i++) {
if (i === 5) {
break;
}
console.log(`Value: ${i}`);
}
// Output: 0, 1, 2, 3, 4