- Home
- /
- If else ladder
JavaScript Tutorial
IINTRODUCTION
JAVASCRIPT VARIABLES
JAVASCRIPT BASICS
JAVASCRIPT OBJECTS
DOM & BOM
OOPs
- Home
- /
- If else ladder
If-else Ladder
Sometimes in your programs, you don’t just want to check one condition—you want to check several, and respond differently to each. That’s where the if...else if...else
ladder comes in.
It’s like giving your code a checklist:
Is this true?
No? Then how about this?
Still no? Maybe this next one?
Okay—if nothing matched, do this final thing.
Syntax Example
Here’s how it looks in code:
if (condition1) {
// do something
} else if (condition2) {
// do something else
} else if (condition3) {
// do another thing
} else {
// if nothing matched, do this
}
The moment JavaScript finds a true condition, it runs that block and skips the rest.
Example
Let’s say you want to categorize a number based on its size:
let x = 10;
if (x > 15) {
console.log("x is greater than 15");
} else if (x > 10) {
console.log("x is greater than 10 but less than or equal to 15");
} else if (x > 5) {
console.log("x is greater than 5 but less than or equal to 10");
} else {
console.log("x is 5 or less");
}
In this case:
x
is 10It’s not greater than 15
It’s not greater than 10
But it is greater than 5, so the third condition runs
Output:
x is greater than 5 but less than or equal to 10
When to Use If-Else Ladders
Use this structure when:
You have more than two conditions
The logic should follow a clear top-down order
Each condition is mutually exclusive (only one should run)