JavaScript Loops & Control Flow

Control flow decides which code runs and how many times. This is where programs stop being calculators and start being programs.

if / else if / else

Conditions are any expression that produces a boolean. Comparisons build them: === !== > < >= <=, combined with && (and), || (or), ! (not).

For a quick either/or there's the ternary operator — an if/else that's also an expression:

JavaScript
const label = age >= 18 ? "adult" : "minor";

switch

Cleaner than an if-chain when comparing one value against many options:

JavaScript
switch (day) {
  case "Saturday":
  case "Sunday":
    console.log("Weekend");
    break;
  case "Monday":
    console.log("Start of the week");
    break;
  default:
    console.log("Regular day");
}

Without break, execution falls through into the next case — sometimes useful (see the grouped weekend cases above), usually a bug.

while and do...while

for — the workhorse

Three parts: start; keep-going condition; step.

JavaScript
for (let i = 0; i < 5; i++) {
  console.log(i);          // 0, 1, 2, 3, 4
}

A classic interview warm-up — FizzBuzz:

Note i % 15 === 0 must be checked first — otherwise 15 matches the % 3 branch and never reaches it.

for...of — looping over collections

When you have an array, don't manage an index yourself:

JavaScript
const dishes = ["momo", "thukpa", "chatpat"];

for (const dish of dishes) {
  console.log(`One plate of ${dish}`);
}

// Need the index too? entries() gives you both:
for (const [i, dish] of dishes.entries()) {
  console.log(`${i + 1}. ${dish}`);
}

To loop over an object's keys/values you first turn it into pairs — covered in the Arrays & Objects chapter.

break and continue

  • break — exit the loop entirely
  • continue — skip to the next iteration
JavaScript
for (const n of [3, 8, -1, 12, -7, 5]) {
  if (n < 0) continue;   // ignore negatives, keep looping
  if (n > 10) break;     // stop at the first number over 10
  console.log(n);        // 3, 8
}

Knowledge Check

4 questions — test your understanding

1

What does this loop print? for (let i = 0; i < 3; i++) console.log(i)

2

Which loop always runs its body at least once?

3

What does continue do inside a loop?

4

If you forget break in a switch case...

Next: Functions