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 which code runs and in what order. JavaScript provides if/else statements and switch statements to branch your program based on conditions.
let temperature = 28;
if (temperature > 30) {
console.log("It's hot outside!");
}
The block inside if only runs when the condition evaluates to true. Curly braces define the block — always use them even for single-line bodies.
let score = 72;
if (score >= 90) {
console.log("A grade");
} else if (score >= 80) {
console.log("B grade");
} else if (score >= 70) {
console.log("C grade");
} else {
console.log("Below C");
}
Only one branch executes — the first one whose condition is true. Once a branch is taken, the rest are skipped entirely.
JavaScript evaluates any value as either truthy or falsy in a boolean context. Falsy values are:
false
0
"" // empty string
null
undefined
NaN
Everything else is truthy, including "0", [], and {}.
let username = "";
if (username) {
console.log("Welcome, " + username);
} else {
console.log("Please enter a username"); // this runs
}
Use switch when comparing a single value against many specific cases:
let 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");
}
The break statement exits the switch block. Without it, execution "falls through" to the next case, which can be used intentionally (as shown above with weekdays) but is often a bug.
let age = 25;
let hasTicket = true;
if (age >= 18 && hasTicket) {
console.log("Entry granted");
}
let isAdmin = false;
let isModerator = true;
if (isAdmin || isModerator) {
console.log("Has elevated access");
}
A common pattern is to return early from a function to avoid deep nesting:
function processOrder(order) {
if (!order) {
return "No order provided";
}
if (!order.isPaid) {
return "Payment required";
}
// main logic here — no deep nesting needed
return "Order processed";
}
Mastering if/else and switch is fundamental. Use guard clauses to keep code readable, and always use strict equality in conditions.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.