Programming Lesson 4: Control flow
How programs make decisions and repeat work safely and readably.
Learning goals
- Use branching and switch statements to choose actions.
- Use loops to repeat work and avoid off-by-one errors.
- Understand
break,continue, and readable condition design.
Branching: if / else / else if
Use if to run code when a condition is true. Use else if to check additional conditions in order, and else as a fallback.
const score = 85;
if (score >= 90) {
console.log('A');
} else if (score >= 75) {
console.log('B');
} else if (score >= 60) {
console.log('C');
} else {
console.log('F');
}
switch
switch is useful when comparing the same value against many possible constants — it can be clearer than long else-if chains.
switch (color) {
case 'red':
console.log('Stop');
break;
case 'green':
console.log('Go');
break;
default:
console.log('Unknown');
}
Off-by-one errors
Common when looping ranges. Prefer clear boundaries and test small inputs. Use inclusive/exclusive naming: for (let i = 0; i < n; i++) iterates n times from 0..n-1.
Designing conditions
Favor readability: name boolean expressions and avoid deeply nested conditions. Example:
// less readable
if (a && (b || c) && !d) { doWork(); }
// more readable
const canProceed = a && (b || c) && !d;
if (canProceed) { doWork(); }
Examples
Grading logic
function grade(score) {
if (score >= 90) return 'A';
if (score >= 80) return 'B';
if (score >= 70) return 'C';
return 'F';
}
Repeat N times
function repeat(n, fn) {
for (let i = 0; i < n; i++) fn(i);
}
repeat(3, i => console.log(i)); // 0,1,2
Iterate an array (light)
const items = [10,20,30];
for (const item of items) {
console.log(item);
}
Practice tasks
- Sum numbers from 1 to N (expected: correct sum for given N).
- Implement FizzBuzz for 1..N (optional classic).
- Find the first item in a list greater than 100 and return its index (or -1 if none).
Common mistakes & debugging
- Off-by-one in loop bounds — test with N=0,1,2.
- Modifying loop variables inside loops leading to unexpected behavior.
- Overusing
break/continuemaking logic harder to follow. - Nested conditions without named booleans; extract and name expressions for clarity.