Last 30 Days
No notifications
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.
# Control Flow & Loops
const score = 78;if (score >= 90) grade = "A";
else if (score >= 75) grade = "B";
else if (score >= 60) grade = "C";
else grade = "F";
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 guardconst label = isAdmin ? "admin" : "user";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";
}
===) for matching.break — without it, execution falls through to the next case.while (n > 0) {
console.log(n--);
}do {
answer = prompt("y/n");
} while (answer !== "y" && answer !== "n"); // runs at least once
for (let i = 0; i < 10; i++) {
console.log(i);
}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);
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()).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)){ … }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
}
}
forEacharr.forEach((item, i) => console.log(i, item));
break or continue. Returning from the callback only exits *that* iteration.for…of or .some() / .find().