Control Flow
Control Flow
Section titled “Control Flow”What it means
Section titled “What it means”Control flow determines the order in which code executes. JavaScript provides conditionals (if/else, switch), loops (for, while, for…of, for…in), and jump statements (break, continue, return).
Examples
Section titled “Examples”// If/elseconst age = 18;if (age >= 18) { console.log("Adult");} else if (age >= 13) { console.log("Teen");} else { console.log("Child");}
// Ternary operatorconst status = age >= 18 ? "Adult" : "Minor";
// Switch statementconst day = "Monday";switch (day) { case "Monday": case "Tuesday": console.log("Start of week"); break; case "Friday": console.log("TGIF!"); break; default: console.log("Midweek");}
// For loopfor (let i = 0; i < 5; i++) { console.log(i);}
// While looplet count = 0;while (count < 5) { console.log(count++);}
// For...of (arrays/iterables)const colors = ["red", "green", "blue"];for (const color of colors) { console.log(color);}
// For...in (object properties)const user = { name: "Alice", age: 25 };for (const key in user) { console.log(`${key}: ${user[key]}`);}Common mistake
Section titled “Common mistake”Using for...in on arrays instead of for...of:
const arr = [10, 20, 30];
// BAD - for...in gives indices (strings!)for (const i in arr) { console.log(typeof i); // "string"}
// GOOD - for...of gives valuesfor (const val of arr) { console.log(val); // 10, 20, 30}Fix: Use for...of for arrays, for...in for objects.
Quick practice
Section titled “Quick practice”-
What’s the difference between
for...ofandfor...in?Answer
`for...of` iterates over values (arrays/iterables); `for...in` iterates over keys (objects). -
Rewrite this with a ternary:
let msg; if (x > 0) { msg = "positive"; } else { msg = "non-positive"; }Answer
`let msg = x > 0 ? "positive" : "non-positive";` -
What does
breakdo in a loop?Answer
Exits the loop immediately; execution continues after the loop.