Skip to content

Control Flow

Scope: if, loops, and switch. All examples were run with Node v24.

if / else if / else

const age = 20;
if (age >= 18) {
  console.log("adult");
} else if (age >= 13) {
  console.log("teenager");
} else {
  console.log("child");
}

Parentheses around the condition are required; braces are technically optional for one line but always use them — the bugs from skipping braces are legendary.

Ternary: if as an expression

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

Handy for simple either/or assignments. If it doesn't fit on one line, use a real if.

Loops

for — counted loops:

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

while — condition loops:

let n = 1;
while (n < 100) {
  n *= 2;
}

for...of — over values (the one you'll use most):

const nums = [10, 20, 30];
for (const v of nums) {
  console.log(v);
}

for...in — over object keys (not array values — a classic mistake):

const user = { name: "Ada", age: 36 };
for (const key in user) {
  console.log(key, user[key]);
}

Use for...of for arrays, for...in for objects, never the reverse.

break and continue

for (const v of [1, 2, 3, 4]) {
  if (v === 3) continue;  // skip 3
  if (v === 4) break;     // stop entirely
  console.log(v);         // 1, 2
}

switch

const day = "Sat";
switch (day) {
  case "Sat":
  case "Sun":
    console.log("weekend");
    break;
  case "Mon":
    console.log("back to work");
    break;
  default:
    console.log("weekday");
}

JavaScript switch falls through without break — cases run into each other. That's usually a bug, occasionally intentional (like "Sat"/"Sun" above). Many teams prefer if/else chains or lookup objects instead:

const labels = { Sat: "weekend", Sun: "weekend", Mon: "back to work" };
console.log(labels[day] ?? "weekday");

The ?? is nullish coalescing: "use the right side if the left is null or undefined." Unlike ||, it doesn't trigger on 0 or "".

Optional chaining: ?.

const city = user?.address?.city;  // undefined if anything is missing

?. short-circuits to undefined instead of throwing when something in the chain is nullish. Essential for nested data from APIs.

Check

  • [ ] You can write all four loop forms and pick the right one
  • [ ] You know why break matters in switch
  • [ ] You can explain ?? vs || and what ?. does

Next: Functions.