Welcome back! 👋 In the previous lesson, you got a broad overview of conditional statements in JavaScript. Now let's go deeper into one of the most-used patterns — the if else ladder!
The if else ladder is how JavaScript handles multiple conditions in sequence. Think of it like a waterfall — JavaScript checks each condition from top to bottom and executes the first block that matches.
Let's master it with real examples and practical exercises!
What is an if else Ladder?
An if else ladder (also called if...else if...else) is a chain of conditions evaluated one after another. JavaScript checks each condition in order and executes only the first matching block. Once a match is found, the rest are completely skipped.
Why You Need It
A basic if...else only gives you two choices — true or false. But real-world programs almost always have more than two possibilities:
- What if a student can get A, B, C, D, or F?
- What if a user can be a Guest, Member, Admin, or Superadmin?
- What if a product is Out of Stock, Low Stock, In Stock, or Overstocked?
That's exactly where the if else ladder shines.
Example:
let marks = 72;
if (marks >= 90) {
console.log("Grade: A");
} else if (marks >= 75) {
console.log("Grade: B");
} else if (marks >= 60) {
console.log("Grade: C"); // ✅ This runs — first true condition
} else if (marks >= 40) {
console.log("Grade: D"); // Skipped
} else {
console.log("Grade: F"); // Skipped
}
// Output: Grade: CSyntax
if (condition1) {
// runs if condition1 is true
} else if (condition2) {
// runs if condition1 is false AND condition2 is true
} else if (condition3) {
// runs if condition1 and condition2 are false AND condition3 is true
} else if (condition4) {
// runs if all above are false AND condition4 is true
} else {
// runs if NONE of the above conditions are true (fallback)
}Key Rules
- You can have as many
else ifblocks as you need - The
elseblock is optional — but it's good practice to include it as a fallback - JavaScript evaluates from top to bottom and stops at the first true condition
- Once a block executes, all remaining blocks are skipped
How JavaScript Evaluates the Ladder
Understanding the evaluation order is critical to writing correct conditions.
let x = 25;
if (x > 50) {
console.log("Greater than 50"); // ❌ false — skip
} else if (x > 30) {
console.log("Greater than 30"); // ❌ false — skip
} else if (x > 20) {
console.log("Greater than 20"); // ✅ true — RUN THIS, stop checking
} else if (x > 10) {
console.log("Greater than 10"); // Never reached
} else {
console.log("10 or less"); // Never reached
}
// Output: Greater than 20Even though x > 10 is also true, JavaScript never checks it because x > 20 matched first.
Real-World Examples
Example 1: Grade Calculator
let marks = 88;
if (marks >= 90) {
console.log("Grade: A+ 🌟 — Outstanding!");
} else if (marks >= 80) {
console.log("Grade: A 🎉 — Excellent!");
} else if (marks >= 70) {
console.log("Grade: B 👍 — Good!");
} else if (marks >= 60) {
console.log("Grade: C 🙂 — Average");
} else if (marks >= 40) {
console.log("Grade: D ⚠️ — Below Average");
} else {
console.log("Grade: F ❌ — Failed. Better luck next time!");
}
// Output: Grade: A 🎉 — Excellent!Example 2: BMI Calculator
let bmi = 27.5;
if (bmi < 18.5) {
console.log("Category: Underweight 🔵");
console.log("Tip: Consider a nutritionist consultation.");
} else if (bmi < 25) {
console.log("Category: Normal weight 🟢");
console.log("Tip: Keep maintaining your healthy lifestyle!");
} else if (bmi < 30) {
console.log("Category: Overweight 🟡");
console.log("Tip: Regular exercise and a balanced diet can help.");
} else if (bmi < 35) {
console.log("Category: Obese (Class I) 🟠");
console.log("Tip: Please consult a doctor.");
} else {
console.log("Category: Obese (Class II+) 🔴");
console.log("Tip: Medical attention is recommended.");
}
// Output: Category: Overweight 🟡
// Tip: Regular exercise and a balanced diet can help.Example 3: Traffic Fine System
let speed = 95; // km/h
let speedLimit = 60;
let excess = speed - speedLimit;
if (speed <= speedLimit) {
console.log("✅ No fine. Drive safe!");
} else if (excess <= 10) {
console.log("⚠️ Warning issued. Fine: ₹500");
} else if (excess <= 20) {
console.log("🚨 Fine: ₹1,000. Slow down!");
} else if (excess <= 40) {
console.log("🚨 Fine: ₹2,000. License points deducted.");
} else {
console.log("🚔 Fine: ₹5,000. License suspended!");
}
// Output: 🚨 Fine: ₹2,000. License points deducted.Example 4: E-commerce Discount System
let cartValue = 3500;
let isMember = true;
let discount;
if (cartValue >= 5000 && isMember) {
discount = 25;
} else if (cartValue >= 5000) {
discount = 20;
} else if (cartValue >= 3000 && isMember) {
discount = 15;
} else if (cartValue >= 3000) {
discount = 10;
} else if (cartValue >= 1000) {
discount = 5;
} else {
discount = 0;
}
let finalPrice = cartValue - (cartValue * discount / 100);
console.log(`Discount: ${discount}%`);
console.log(`Final Price: ₹${finalPrice}`);
// Output: Discount: 15%
// Final Price: ₹2975Example 5: User Role Access Control
let role = "editor";
if (role === "superadmin") {
console.log("Access: Everything — manage users, settings, and data 🔑");
} else if (role === "admin") {
console.log("Access: Manage users and content 🛠️");
} else if (role === "editor") {
console.log("Access: Create and edit content ✏️");
} else if (role === "viewer") {
console.log("Access: View content only 👁️");
} else {
console.log("Access: Denied ❌ — Unknown role");
}
// Output: Access: Create and edit content ✏️if else Ladder vs Nested if
These two look similar but behave very differently — don't confuse them!
if else Ladder (Flat — Preferred ✅)
let score = 75;
if (score >= 90) {
console.log("A grade");
} else if (score >= 75) {
console.log("B grade"); // ✅ This runs
} else if (score >= 60) {
console.log("C grade");
} else {
console.log("F grade");
}Nested if (Deep — Use Sparingly ⚠️)
let score = 75;
let attendance = 80;
if (score >= 75) {
if (attendance >= 75) {
console.log("Eligible for exam 🎓"); // ✅ Both conditions met
} else {
console.log("Score OK but attendance low ⚠️");
}
} else {
console.log("Score too low ❌");
}When to use which:
- Use if else ladder when conditions are mutually exclusive (only one should run)
- Use nested if when a second condition only makes sense if the first is already true
Combining Conditions with Logical Operators
You can make each else if more powerful by combining conditions.
Using && (AND)
let age = 22;
let hasId = true;
let hasMembership = true;
if (age >= 21 && hasId && hasMembership) {
console.log("Full access granted 🟢");
} else if (age >= 18 && hasId) {
console.log("Limited access granted 🟡");
} else if (age >= 18) {
console.log("Please show your ID 🪪");
} else {
console.log("Access denied — must be 18+ 🔴");
}
// Output: Full access granted 🟢Using || (OR)
let day = "Saturday";
if (day === "Saturday" || day === "Sunday") {
console.log("Weekend — office closed 🏖️");
} else if (day === "Monday" || day === "Friday") {
console.log("Start or end of week — busy day! 💪");
} else {
console.log("Midweek — regular working day 💼");
}
// Output: Weekend — office closed 🏖️The Order of Conditions Matters!
One of the most common bugs with if else ladders is writing conditions in the wrong order.
Wrong Order ❌
let marks = 95;
if (marks >= 40) {
console.log("Grade: D"); // ✅ This runs — but it's wrong!
} else if (marks >= 60) {
console.log("Grade: C"); // Never checked
} else if (marks >= 75) {
console.log("Grade: B"); // Never checked
} else if (marks >= 90) {
console.log("Grade: A"); // Never checked — even though marks = 95!
}
// Output: Grade: D ← Bug! Should be Grade: ACorrect Order ✅ (Most restrictive first)
let marks = 95;
if (marks >= 90) {
console.log("Grade: A"); // ✅ This runs correctly
} else if (marks >= 75) {
console.log("Grade: B");
} else if (marks >= 60) {
console.log("Grade: C");
} else if (marks >= 40) {
console.log("Grade: D");
}
// Output: Grade: A ✅Golden Rule: When working with ranges, always put the most restrictive (highest/lowest) condition first.
Always Include an else Fallback
The final else acts as a safety net — it catches anything that doesn't match any condition above.
Without else (Risky ⚠️)
let status = "unknown";
if (status === "active") {
console.log("User is active");
} else if (status === "inactive") {
console.log("User is inactive");
} else if (status === "banned") {
console.log("User is banned");
}
// If status = "unknown" — nothing prints! Silent failure.With else (Safe ✅)
let status = "unknown";
if (status === "active") {
console.log("User is active ✅");
} else if (status === "inactive") {
console.log("User is inactive 💤");
} else if (status === "banned") {
console.log("User is banned 🚫");
} else {
console.log("Unknown status — please contact support ⚠️"); // ✅ Safe fallback
}
// Output: Unknown status — please contact support ⚠️Common Mistakes
Mistake 1: Wrong Condition Order (Range Bugs)
let temp = 38;
// ❌ Wrong — broader condition catches everything first
if (temp > 20) {
console.log("Warm"); // Always runs for temp > 20, never reaches "Hot"
} else if (temp > 35) {
console.log("Hot"); // Dead code — never reached!
}
// ✅ Correct — most specific first
if (temp > 35) {
console.log("Hot 🔥");
} else if (temp > 20) {
console.log("Warm ☀️");
}Mistake 2: Using if Instead of else if for Related Conditions
let score = 85;
// ❌ Wrong — uses separate if, checks ALL conditions every time
if (score >= 90) {
console.log("A grade");
}
if (score >= 75) {
console.log("B grade"); // Also runs! score is also >= 75
}
if (score >= 60) {
console.log("C grade"); // Also runs! score is also >= 60
}
// Output: B grade C grade ← Multiple grades printed!
// ✅ Correct — else if stops after first match
if (score >= 90) {
console.log("A grade");
} else if (score >= 75) {
console.log("B grade"); // ✅ Only this runs
} else if (score >= 60) {
console.log("C grade");
}
// Output: B grade ✅Mistake 3: Missing {} Braces on Multi-line Blocks
let x = 10;
// ❌ Dangerous — only first line is in the if block
if (x > 5)
console.log("Greater than 5");
console.log("This ALWAYS runs!"); // Not part of the if block!
// ✅ Always use braces
if (x > 5) {
console.log("Greater than 5");
console.log("This only runs if x > 5.");
}Mistake 4: Comparing Strings with == instead of ===
let input = "5"; // from user input — it's a string
// ❌ Might work due to coercion, but unreliable
if (input == 5) {
console.log("Five");
}
// ✅ Always use === for safe, predictable comparison
if (input === "5") {
console.log("Five ✅");
}Practical Exercise: Build a Complete Calculator Logic
Create a file called if-else-ladder.js:
// 🎯 Exercise: Complete Real-World if else Ladder System
// 1. Age Category Classifier
function getAgeCategory(age) {
console.log(`\n--- Age: ${age} ---`);
if (age < 0) {
console.log("Invalid age ❌");
} else if (age <= 2) {
console.log("Category: Infant 👶");
} else if (age <= 12) {
console.log("Category: Child 🧒");
} else if (age <= 17) {
console.log("Category: Teenager 🧑");
} else if (age <= 35) {
console.log("Category: Young Adult 🙋");
} else if (age <= 60) {
console.log("Category: Middle-Aged Adult 👨");
} else if (age <= 80) {
console.log("Category: Senior 👴");
} else {
console.log("Category: Elderly 🧓 — Legend!");
}
}
getAgeCategory(-1);
getAgeCategory(1);
getAgeCategory(10);
getAgeCategory(16);
getAgeCategory(25);
getAgeCategory(50);
getAgeCategory(70);
getAgeCategory(90);
// 2. Internet Speed Checker
function checkInternetSpeed(mbps) {
console.log(`\n--- Speed: ${mbps} Mbps ---`);
if (mbps <= 0) {
console.log("Status: No Connection 🔴");
} else if (mbps < 1) {
console.log("Status: Very Slow 🐌 — barely functional");
} else if (mbps < 10) {
console.log("Status: Slow 🟠 — basic browsing only");
} else if (mbps < 50) {
console.log("Status: Moderate 🟡 — good for most tasks");
} else if (mbps < 200) {
console.log("Status: Fast 🟢 — great for HD streaming");
} else {
console.log("Status: Ultra Fast ⚡ — ready for anything!");
}
}
checkInternetSpeed(0);
checkInternetSpeed(0.5);
checkInternetSpeed(5);
checkInternetSpeed(25);
checkInternetSpeed(100);
checkInternetSpeed(500);Run it:
node if-else-ladder.jsExpected Output:
--- Age: 25 ---
Category: Young Adult 🙋
--- Speed: 100 Mbps ---
Status: Fast 🟢 — great for HD streamingKey Takeaways
Congratulations! 🎉 You now have a solid grasp of the if else ladder in JavaScript.
✅ if else ladder chains multiple conditions together — only the first true condition executes.
✅ Evaluation Order:
- JavaScript checks conditions top to bottom
- Stops at the first true condition
- The rest are completely skipped
✅ The else block:
- Optional but highly recommended
- Acts as a safe fallback for unmatched conditions
✅ Order matters:
- Always put the most restrictive condition first when working with ranges
- Wrong order leads to silent bugs that are hard to catch
✅ Use else if (not separate if) for mutually exclusive conditions:
- Separate
ifstatements check every condition independently else ifstops as soon as one matches
✅ Combine with logical operators:
&&— all sub-conditions must be true||— at least one sub-condition must be true
Best Practices
- ✅ Always use
{}braces for every block — even single-line ones - ✅ Put the most restrictive condition first (especially for number ranges)
- ✅ Always include an
elsefallback to handle unexpected values - ✅ Use
else iffor mutually exclusive conditions — not separateifstatements - ✅ Use
===instead of==for comparisons - ✅ Keep conditions simple and readable — one clear check per branch
- ✅ If the ladder gets longer than 5–6 branches, consider a
switchor a lookup object - ✅ Add comments when conditions aren't immediately obvious to other developers
What's Next?
Excellent work! 🎉 You've mastered the if else ladder — one of the most practical tools in JavaScript.
In the next lessons, we'll cover the remaining conditional tools:
- Ternary Operator — writing super clean one-line conditions
- Switch Case — a cleaner alternative when matching exact values
Keep experimenting with different conditions — the more you practice, the more natural this becomes!