Else If for Multiple Conditions
What you'll learn: How to test multiple different conditions in sequence using else if to handle more than just two possible outcomes.
Beyond Simple If/Else
You've already seen how if tests one condition and else handles "everything else." But what if you need to check several specific conditions, not just two possibilities?
The else if clause lets you chain additional tests together. JavaScript evaluates them top-to-bottom, stopping at the first condition that's true.
How Else If Works
let score = 85;
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("Need improvement");
}
// Output: "B grade"
JavaScript checks each condition in order:
- Is
score >= 90? No (85 < 90), keep going - Is
score >= 80? Yes! Execute this block and skip the rest
Think of it like a multiple-choice quiz where you stop at the first correct answer.
Why Order Matters
let age = 25;
if (age >= 0) {
console.log("Valid age");
} else if (age >= 18) {
console.log("Adult"); // This never runs!
}
The first condition catches all positive ages, so the second check never gets a chance. Always order from most specific to most general.
Key Differences from Multiple Ifs
Using else if means only one block executes. Separate if statements would test every condition independently.
Key Takeaway: Use else if to chain multiple mutually exclusive conditions together, testing each in sequence until one passes—or falling through to a final else if none do.