If-Else Ladder
Handling Multiple Conditions
Sometimes a simple "yes or no" (if/else) isn't enough. You might have three, four, or more possible outcomes. This is where the else if statement comes in, creating what we call an "If-Else Ladder".
How It Works
The browser checks the first if condition. If it's true, it runs that block and skips the rest. If it's false, it moves to the next else if condition. If none of the conditions are true, it runs the final else block (if you provided one).
Example
Imagine a grading system based on a student's score:
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
// Outputs: "Grade: B"
Important Note on Order
The order of your conditions is crucial! JavaScript evaluates from top to bottom. If we put (score >= 70) at the very top, our 85-scoring student would get a "C" because that condition would evaluate to true first, and the rest of the ladder would be entirely skipped! Always order your conditions logically, usually from most specific to least specific.
💡 Himanshu's Tip:
Order is everything in an if-else ladder! Always put your most specific, restrictive conditions at the very top. If you put a broad condition at the top, the code will never reach the specific ones below it.
Interview Questions
- In an if-else ladder, what happens after the first true condition is met and executed?
- Why is the order of conditions important in an if-else ladder?
- Is the final
elseblock mandatory?