Skip to content

Control Flow

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).

// If/else
const age = 18;
if (age >= 18) {
console.log("Adult");
} else if (age >= 13) {
console.log("Teen");
} else {
console.log("Child");
}
// Ternary operator
const status = age >= 18 ? "Adult" : "Minor";
// Switch statement
const 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 loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// While loop
let 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]}`);
}

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 values
for (const val of arr) {
console.log(val); // 10, 20, 30
}

Fix: Use for...of for arrays, for...in for objects.

  1. What’s the difference between for...of and for...in?

    Answer`for...of` iterates over values (arrays/iterables); `for...in` iterates over keys (objects).
  2. Rewrite this with a ternary: let msg; if (x > 0) { msg = "positive"; } else { msg = "non-positive"; }

    Answer`let msg = x > 0 ? "positive" : "non-positive";`
  3. What does break do in a loop?

    AnswerExits the loop immediately; execution continues after the loop.