You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Control flow determines the order in which statements are executed. By using conditionals and loops, you can make your programs react to different inputs and repeat tasks efficiently.
The most fundamental conditional statement:
const temperature = 28;
if (temperature > 30) {
console.log("It's hot!");
} else if (temperature > 20) {
console.log("It's warm.");
} else if (temperature > 10) {
console.log("It's cool.");
} else {
console.log("It's cold!");
}
// Output: "It's warm."
if() is converted to a boolean.else if and else are optional.JavaScript converts any value to a boolean when needed. Values that convert to false are called falsy:
| Falsy Values |
|---|
false |
0, -0, 0n |
"" (empty string) |
null |
undefined |
NaN |
Everything else is truthy — including "0", "false", empty arrays [], and empty objects {}.
if ("hello") {
console.log("Truthy!"); // this runs
}
if ("") {
console.log("This never runs");
}
A compact alternative to if/else for simple assignments:
const age = 20;
const status = age >= 18 ? "adult" : "minor";
// "adult"
Syntax: condition ? valueIfTrue : valueIfFalse
Use switch when comparing one value against many possible matches:
const day = "Monday";
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
console.log("Weekday");
break;
case "Saturday":
case "Sunday":
console.log("Weekend");
break;
default:
console.log("Unknown day");
}
case uses strict equality (===).break, execution falls through to the next case.default case for unexpected values.The classic loop with an initialiser, condition, and update expression:
for (let i = 0; i < 5; i++) {
console.log(i);
}
// 0, 1, 2, 3, 4
for (initialiser; condition; update) {
// body
}
Use while when you do not know how many iterations are needed:
let count = 0;
while (count < 3) {
console.log(count);
count++;
}
// 0, 1, 2
Guarantees the body executes at least once because the condition is checked after the first iteration:
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.