JavaScript FoundationsLesson 1.5
Control flow: if, else, switch, and loops in JavaScript
if-else, switch statement, for loop, while loop, do-while, for-of, for-in, break, continue, truthy and falsy values
Directing Execution Flow
Control flow determines which code runs and how many times. Every meaningful program branches and repeats. JavaScript gives you conditional statements and several loop constructs to handle both.
Conditionals
const score = 72;
if (score >= 90) {
console.log("A");
} else if (score >= 70) {
console.log("B");
} else {
console.log("C or below");
}
switch (day) {
case "Mon": console.log("Start of week"); break;
case "Fri": console.log("End of week"); break;
default: console.log("Midweek");
}
Loops
// classic for — when you need the index
for (let i = 0; i < 5; i++) {
console.log(i);
}
// for-of — iterating values of an iterable
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}
// while — when stop condition is not count-based
let n = 1;
while (n < 100) {
n *= 2;
}
console.log(n); // 128
Truthy and Falsy
Six values are falsy in JavaScript: false, 0, "", null, undefined, and NaN. Everything else is truthy. This is what if evaluates — not just strict booleans. Use break to exit a loop early and continue to skip to the next iteration when a condition is met inside the loop body.
