Control Flow
Make decisions and repeat work with conditions, loops, and early exits.
Control flow determines which statements run and how often. Clear conditions and early exits keep the happy path easy to follow.
Branch with conditions
access.js
const lessonsFinished = 8;
if (lessonsFinished === 0) {
console.log("Start the course");
} else if (lessonsFinished < 8) {
console.log("Keep going");
} else {
console.log("Course complete");
}
Falsy values are false, 0, -0, 0n, an empty string, null, undefined, and NaN. Everything else is truthy, including empty arrays and objects.
Choose among known cases
theme.js
switch (theme) {
case "dark":
applyDarkTheme();
break;
case "light":
applyLightTheme();
break;
default:
applySystemTheme();
}
Repeat safely
lessons.js
const lessons = ["HTML", "CSS", "JavaScript"];
for (const lesson of lessons) {
console.log(lesson);
}
for (let index = 0; index < lessons.length; index += 1) {
console.log(index, lessons[index]);
}
Use for...of for values. Use a counted loop when the index matters. while is useful when repetition depends on a changing condition rather than a collection.
Keep this
Write explicit branches, remember truthiness rules, and choose the loop that makes termination obvious.
学习位置已保存在此设备上。