When there are more than two outcomes, chain conditions with else if. JavaScript checks them from top to bottom and runs the first block whose condition is true, then skips the rest.
const score = 78;
if (score >= 90) {
console.log("Grade A");
} else if (score >= 80) {
console.log("Grade B");
} else if (score >= 70) {
console.log("Grade C"); // → Grade C
} else {
console.log("Needs work");
}
Because the chain stops at the first match, the order matters. A score of 95 matches the first test, so it never reaches the others. If you wrote score >= 70 first, every high score would be a “C”.
The final else
else at the end is optional. It catches everything that did not match.
Nested conditions
You can put an if inside another if.
const isLoggedIn = true;
const isAdmin = false;
if (isLoggedIn) {
if (isAdmin) {
console.log("Show admin panel");
} else {
console.log("Show dashboard"); // → Show dashboard
}
} else {
console.log("Show login form");
}
Keep nesting shallow
Deep nesting is hard to read. Two ways to flatten it:
1. Combine conditions with &&.
if (isLoggedIn && isAdmin) {
showAdminPanel();
}
2. Return early (inside a function), so the main path stays unindented.
function describeUser(user) {
if (!user) {
return "No user";
}
if (!user.isActive) {
return "Inactive";
}
return "Active: " + user.name;
}
console.log(describeUser(null)); // → No user
console.log(describeUser({ name: "Maya", isActive: false })); // → Inactive
console.log(describeUser({ name: "Maya", isActive: true })); // → Active: Maya
Exercise: shipping cost
Write a function shipping(total) that returns 0 if the total is 50 or more, 5 if it is 20 or more, and 10 otherwise.
Show a possible solution
function shipping(total) {
if (total >= 50) return 0;
if (total >= 20) return 5;
return 10;
}
console.log(shipping(60)); // → 0
console.log(shipping(30)); // → 5
console.log(shipping(5)); // → 10