Control flow statements allow your program to make decisions and execute different blocks of code based on certain conditions.
4.1 if, else if, else statements
The if statement executes a block of code if a specified condition is true. You can extend it with else if for multiple conditions and else for a default case.
-
Syntax
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition1 is false AND condition2 is true
} else {
// Code to execute if all conditions are false
}
-
Example
let temperature = 25;
if (temperature > 30) {
console.log("It's hot!");
} else if (temperature > 20) {
console.log("It's warm.");
} else {
console.log("It's cool.");
}
// Output: It's warm.
4.2 switch statements
The switch statement is an alternative to long if-else if chains when you're checking a single variable against multiple possible values.
-
Syntax
switch (expression) {
case value1:
// Code if expression matches value1
break; // Important: exits the switch block
case value2:
// Code if expression matches value2
break;
default:
// Code if no match is found
}
-
Example
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the week.");
break;
case "Friday":
console.log("Almost weekend!");
break;
default:
console.log("Mid-week day.");
}
// Output: Start of the week.
The break keyword is crucial to prevent "fall-through" where code from subsequent case blocks would also execute.
4.3 Conditional (Ternary) Operator for Decisions
As seen in Chapter 3, the ternary operator (condition ? valueIfTrue : valueIfFalse;) is a concise way to make simple conditional assignments or expressions.