Notifications

No notifications

/Phase 1

Control Flow & Loops

Decisions and repetition — if/else, switch, and the loop family (for, while, for…of, for…in). Modern JavaScript leans on for…of for iterating values and array methods (map/filter/reduce — covered later) for transforming, but knowing every form keeps you fluent.

On this page

Detailed Theory

# Control Flow & Loops

if / else if / else

const score = 78;

if (score >= 90) grade = "A"; else if (score >= 75) grade = "B"; else if (score >= 60) grade = "C"; else grade = "F";

Truthy / falsy

Conditions don't need to be booleans — they're coerced. The 6 falsy values:
false   0   ""   null   undefined   NaN
Everything else is truthy — including "0", "false", [], {}.

if (user) { … }           // user is set
if (arr.length) { … }     // not empty
if (!str) return;          // early-exit guard

Ternary — small inline if

const label = isAdmin ? "admin" : "user";

switch

switch (status) {
  case "open":
  case "in-review":            // fall-through — both share the body
    color = "blue";
    break;
  case "merged":
    color = "green";
    break;
  case "closed":
    color = "red";
    break;
  default:
    color = "gray";
}
  • Uses strict equality (===) for matching.
  • Don't forget break — without it, execution falls through to the next case.

while / do-while

while (n > 0) {
    console.log(n--);
}

do { answer = prompt("y/n"); } while (answer !== "y" && answer !== "n"); // runs at least once

Classic for

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

for…of — iterate VALUES (preferred for arrays + iterables)

const fruits = ["apple", "banana", "cherry"];
for (const f of fruits) {
    console.log(f);
}

// works on strings, Maps, Sets, NodeLists, generators for (const ch of "hello") console.log(ch);

for…in — iterate KEYS (objects)

const user = { id: 1, name: "alice", admin: true };
for (const key in user) {
    console.log(key, user[key]);
}
> ⚠️ Don't use for…in on arrays — it walks all enumerable string keys, including inherited ones. Use for…of (or .forEach / .entries()).

entries / keys / values

for (const [i, value] of arr.entries()) { … }
for (const key   of Object.keys(user))   { … }
for (const value of Object.values(user)) { … }
for (const [k,v] of Object.entries(user)){ … }

break / continue (and labels)

for (let i = 0; i < 10; i++) {
    if (i === 3) continue;     // skip
    if (i === 7) break;        // exit loop
    console.log(i);            // 0 1 2 4 5 6
}

outer: for (const row of grid) { for (const cell of row) { if (cell === target) break outer; // exit BOTH loops } }

A note on forEach

arr.forEach((item, i) => console.log(i, item));
  • Cannot break or continue. Returning from the callback only exits *that* iteration.
  • For early-exit, use for…of or .some() / .find().