3.6 Conditional Branches: if-else
Sections 3.4 and 3.5 taught you how to build expressions that produce values, including boolean values like score >= 60. A branch uses those boolean values to decide which path the program takes.
Useful programs branch constantly: a login page accepts or rejects a password, a checkout page shows an error when the cart is empty, and a game chooses whether the player has won.
Drag the score in the lab below and watch the program enter a different branch.
The basic if
if (condition) {
// runs only when condition is true
}Example:
const age = 20;
if (age >= 18) {
console.log("You can create an account");
}The code inside { ... } is a block. JavaScript runs that block only when the condition is true.
if-else
Use else when you need one path for success and another path for failure:
const password = "leaflet2026";
if (password.length >= 8) {
console.log("Password length is OK");
} else {
console.log("Password is too short");
}else-if chains
When there are more than two cases, use else if:
const score = 75;
if (score >= 90) {
console.log("Excellent");
} else if (score >= 80) {
console.log("Good");
} else if (score >= 60) {
console.log("Pass");
} else {
console.log("Fail");
}JavaScript checks the conditions from top to bottom. Once it finds the first true branch, it runs that block and skips the rest.
That means order matters. If you put score >= 60 before score >= 90, then a score of 95 would match the 60 branch first and never reach the excellent branch.
Branches in web pages
In browser code, conditions often guard user actions:
const email = document.querySelector("#email").value;
const message = document.querySelector("#message");
if (email === "") {
message.textContent = "Please enter your email.";
} else if (!email.includes("@")) {
message.textContent = "Email must contain @.";
} else {
message.textContent = "Thanks!";
}Notice that ===, !, and method calls such as .includes("@") are only tools for building the condition. The if statement decides what to do with the result.
Nested conditions
Sometimes one decision belongs inside another:
const loggedIn = true;
const isAdmin = false;
if (loggedIn) {
if (isAdmin) {
console.log("Show admin dashboard");
} else {
console.log("Show personal dashboard");
}
} else {
console.log("Show sign-in page");
}Nested conditions are useful, but too many levels become hard to read. When the logic grows, name important conditions with variables:
const canSeeAdminDashboard = loggedIn && isAdmin;