← Back to the Build Your Homepage series
EPISODE 02
if · switch · for · while · ternary

Control Flow

Make decisions and repeat actions: if/else chains, switch, for/of/in, while, and the ternary expression for one-liners.

control flowifswitchforwhile
Duration
About 1.5 hours
Level
📊 Beginner
Prerequisite
🎯 js-01
OUTCOME
Choose the right control structure for each problem

What you'll learn

  • 1Write clean if/else chains and use switch when appropriate
  • 2Loop with for, for...of, for...in correctly
  • 3Use the ternary expression for concise conditionals
  • 4Break and continue to control loop flow

1. if / else / ternary

javascript
if (score >= 90) {
  grade = "A";
} else if (score >= 80) {
  grade = "B";
} else {
  grade = "F";
}

// Ternary for short value pickers
const label = age >= 18 ? "adult" : "minor";

2. switch

javascript
switch (day) {
  case "Sat":
  case "Sun":
    type = "weekend";
    break;
  default:
    type = "weekday";
}
⚠️

Always include break — without it, execution "falls through" to the next case, which is a frequent source of bugs.

3. Loops

javascript
// classic for
for (let i = 0; i < 5; i++) { console.log(i); }

// iterate values (preferred for arrays)
const items = ["a", "b", "c"];
for (const x of items) { console.log(x); }

// iterate keys (for objects)
const user = { name: "Alice", age: 30 };
for (const key in user) { console.log(key, user[key]); }

// while
let n = 10;
while (n > 0) { n--; }

4. break and continue

javascript
for (const n of nums) {
  if (n < 0) continue;   // skip this iteration
  if (n > 100) break;    // stop looping
  console.log(n);
}
Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub ↗