40 Mins beginner
5. Control Flow
Logic
Control Flow
Control flow determines which lines of code run based on specific conditions. It allows your application to make decisions dynamically.
๐ If / Else Statements
The if statement checks a condition. If it evaluates to true, the code block runs. Otherwise, it moves to else if or else.
const batteryLevel = 15;
if (batteryLevel > 50) {
console.log("Battery is healthy.");
} else if (batteryLevel > 20) {
console.log("Battery is getting low.");
} else {
console.log("Critical battery! Plug in charger.");
}
OutputCritical battery! Plug in charger.
๐ฏ The Switch Statement
When you need to check a single variable against many possible exact values, a switch statement is much cleaner than a massive chain of if/else statements.
const role = "editor";
switch (role) {
case "admin":
console.log("Full access granted.");
break;
case "editor":
console.log("You can edit content.");
break;
case "guest":
console.log("Read-only access.");
break;
default:
console.log("Role not recognized.");
}
OutputYou can edit content.
โ ๏ธDon't forget to break! If you omit the
break keyword, JavaScript will continue executing the code in the cases below it, regardless of whether they match!Knowledge Check
Ready to test your understanding of 5. Control Flow?