JavaScript Notes
Learn JavaScript nested if statements with flowcharts, multi-level decision trees, real-world examples, when to refactor, common mistakes, and interview Q&A for beginners.
A nested if statement is an if (or if-else) placed inside another if block. It allows you to check multiple conditions in a hierarchical, step-by-step way — like a decision tree.
Simple definition: "IF condition A is true, THEN check condition B, and IF B is also true, do something."
📝 Syntax
if (conditionA) {
// conditionA is true
if (conditionB) {
// BOTH A and B are true
} else {
// A is true, but B is false
}
} else {
// conditionA is false
}💡 Real World Analogy
Analogy: Getting into a concert:
- Gate 1 (outer if): Do you have a ticket? → If NO, go home (else). If YES...
- Gate 2 (nested if): Is it a VIP ticket? → If YES, go to VIP section. If NO, go to general area.
You only reach Gate 2 after passing Gate 1!
✅ Basic Examples
Example 1: Two-Level Age & ID Check
let age = 20;
let hasID = true;
if (age >= 18) {
console.log("Age requirement passed ✓");
if (hasID) {
console.log("ID verified ✓");
console.log("Entry GRANTED! 🎉");
} else {
console.log("No valid ID ✗");
console.log("Entry DENIED!");
}
} else {
console.log("Under 18 ✗");
console.log("Entry DENIED!");
}Age requirement passed ✓ ID verified ✓ Entry GRANTED! 🎉
Example 2: Number Classification (Positive/Negative, Even/Odd)
let num = -7;
if (num !== 0) {
if (num > 0) {
console.log(num, "is positive.");
if (num % 2 === 0) {
console.log("It is also even.");
} else {
console.log("It is also odd.");
}
} else {
console.log(num, "is negative.");
if (num % 2 === 0) {
console.log("It is also even.");
} else {
console.log("It is also odd.");
}
}
} else {
console.log("The number is zero.");
}-7 is negative. It is also odd.
Example 3: Login System (Three Levels Deep)
let isLoggedIn = true;
let role = "admin";
let hasTwoFactor = true;
if (isLoggedIn) {
console.log("User is logged in ✓");
if (role === "admin") {
console.log("Admin role detected ✓");
if (hasTwoFactor) {
console.log("2FA verified ✓");
console.log("→ Full admin dashboard access granted");
} else {
console.log("2FA required for admin access");
console.log("→ Please enable two-factor authentication");
}
} else {
console.log("Standard user → Redirect to user dashboard");
}
} else {
console.log("Not logged in → Redirect to login page");
}User is logged in ✓ Admin role detected ✓ 2FA verified ✓ → Full admin dashboard access granted
🌳 Visualizing the Decision Tree
For the login example above:
🏗️ Practical Programs
Program 1: Grade and Pass/Fail with Attendance
let marks = 78;
let attendance = 65;
if (marks >= 50) {
if (attendance >= 75) {
console.log("Result: PASS ✓");
if (marks >= 90) {
console.log("Distinction!");
} else if (marks >= 75) {
console.log("First Class!");
} else {
console.log("Second Class.");
}
} else {
console.log("Result: DETAINED (attendance shortage)");
console.log(`Attendance: ${attendance}% (minimum 75% required)`);
}
} else {
console.log("Result: FAIL (marks below 50)");
}Result: PASS ✓ First Class!
Program 2: E-Commerce Discount Logic
let isMember = true;
let cartValue = 1200;
let couponCode = "SAVE20";
let discount = 0;
let message = "";
if (isMember) {
if (cartValue >= 1000) {
if (couponCode === "SAVE20") {
discount = cartValue * 0.20;
message = "Member + ₹1000+ cart + SAVE20 coupon = 20% off";
} else {
discount = cartValue * 0.15;
message = "Member + ₹1000+ cart = 15% off";
}
} else {
discount = cartValue * 0.05;
message = "Member discount = 5% off";
}
} else {
if (cartValue >= 2000) {
discount = cartValue * 0.10;
message = "Non-member with ₹2000+ cart = 10% off";
} else {
message = "No discount for non-members under ₹2000";
}
}
console.log(message);
console.log(`Cart: ₹${cartValue}`);
console.log(`Discount: ₹${discount}`);
console.log(`Final: ₹${cartValue - discount}`);Member + ₹1000+ cart + SAVE20 coupon = 20% off Cart: ₹1200 Discount: ₹240 Final: ₹960
🔧 Refactoring Nested If — Better Approaches
Deep nesting is hard to read. Here are cleaner alternatives:
Original (Deeply Nested)
function processUser(user) {
if (user) {
if (user.isActive) {
if (user.age >= 18) {
if (user.hasVerifiedEmail) {
console.log("User can proceed: " + user.name);
}
}
}
}
}✅ Refactored with Guard Clauses (Early Return)
function processUser(user) {
if (!user) { console.log("No user provided"); return; }
if (!user.isActive) { console.log("User is not active"); return; }
if (user.age < 18) { console.log("User is underage"); return; }
if (!user.hasVerifiedEmail) { console.log("Email not verified"); return; }
console.log("User can proceed:", user.name);
}
processUser({ name: "Priya", isActive: true, age: 22, hasVerifiedEmail: true });
processUser({ name: "Raj", isActive: true, age: 15, hasVerifiedEmail: true });User can proceed: Priya User is underage
Guard clauses reduce nesting from 4 levels to 0 levels!
✅ Refactored with Combined AND Conditions
function canGetLoan(age, income, creditScore, hasJob) {
// Instead of nested ifs, combine conditions
if (age >= 21 && income >= 30000 && creditScore >= 650 && hasJob) {
console.log("Loan APPROVED ✓");
} else {
console.log("Loan DENIED ✗");
if (age < 21) console.log(" - Age requirement not met (min 21)");
if (income < 30000) console.log(" - Income too low (min ₹30,000)");
if (creditScore < 650) console.log(" - Credit score too low (min 650)");
if (!hasJob) console.log(" - Employment required");
}
}
canGetLoan(25, 45000, 700, true);
canGetLoan(19, 25000, 600, false);Loan APPROVED ✓ Loan DENIED ✗ - Age requirement not met (min 21) - Income too low (min ₹30,000) - Credit score too low (min 650) - Employment required
❌ Common Mistakes
Mistake 1: Dangling Else Problem
// ❌ Ambiguous — which if does the else belong to?
let a = true;
let b = false;
if (a)
if (b)
console.log("Both true");
else
console.log("Where does this else belong?"); // belongs to inner if!
// ✅ CLEAR — always use braces to remove ambiguity
if (a) {
if (b) {
console.log("Both true");
} else {
console.log("a is true, b is false"); // clearly belongs to inner if
}
}Where does this else belong? a is true, b is false
Mistake 2: Too Deep — Hard to Read and Maintain
// ❌ BAD — 5 levels deep, impossible to read
if (level1) {
if (level2) {
if (level3) {
if (level4) {
if (level5) {
console.log("Finally doing something!");
}
}
}
}
}
// ✅ GOOD — flatten with early returns or combined conditionsRule of thumb: If you have more than 2-3 levels of nesting, refactor using guard clauses, && operators, or helper functions.🧩 Practice Problems
Problem 1: Triangle Type Classifier
Isosceles triangle
Problem 2: ATM Transaction
let isAuthenticated = true;
let balance = 5000;
let withdrawAmount = 2000;
let dailyLimit = 3000;
if (isAuthenticated) {
if (withdrawAmount <= balance) {
if (withdrawAmount <= dailyLimit) {
balance -= withdrawAmount;
console.log(`Withdrawal of ₹${withdrawAmount} successful!`);
console.log(`Remaining balance: ₹${balance}`);
} else {
console.log(`Exceeds daily limit of ₹${dailyLimit}`);
}
} else {
console.log("Insufficient balance");
}
} else {
console.log("Authentication failed. Please use your PIN.");
}Withdrawal of ₹2000 successful! Remaining balance: ₹3000
🎤 Interview Questions
Q1. What is a nested if statement? > A nested if is an if statement placed inside another if's code block. It allows checking additional conditions that only matter when the outer condition is true.
Q2. What is the "dangling else" problem? > When an else exists without braces, it's ambiguous which if it belongs to. In JavaScript, else always belongs to the nearest preceding if. Always use curly braces to avoid this ambiguity.
Q3. How many levels of nesting are acceptable? > Generally 2-3 levels. Beyond that, code becomes hard to read and maintain. Refactor with guard clauses (early returns), combined &&/|| conditions, or helper functions.
Q4. What are guard clauses and how do they reduce nesting? > Guard clauses are early return statements that check for invalid conditions upfront. Instead of wrapping the happy path in nested ifs, you "return early" for invalid cases, keeping the main logic at the top level with minimal nesting.
Q5. What is the difference between nested if and else-if? > else-if creates sequential checks (only one runs). Nested if creates hierarchical checks — inner conditions are only checked when outer conditions pass. Use nested if when inner conditions depend on outer ones; use else-if when conditions are independent alternatives.
Q6. Can you avoid nested ifs entirely? > Often yes — using && (AND) to combine conditions, using the switch statement, or refactoring with early returns. But sometimes nested ifs are the clearest way to express hierarchical logic.
Q7. What is the output?
let x = 5;
if (x > 0) {
if (x > 10) {
console.log("Greater than 10");
} else {
console.log("Between 1 and 10");
}
} else {
console.log("Zero or negative");
}Between 1 and 10— x=5 passesx > 0but failsx > 10.
🔑 Key Takeaways
| Concept | Detail |
|---|---|
| What it is | An if inside another if block |
| When to use | When inner condition depends on outer condition |
| Dangling else | Always use {} to avoid ambiguity |
| Max depth | 2-3 levels before refactoring |
| Guard clauses | Early returns to reduce nesting |
| Combined conditions | Use && to flatten simple nested checks |
💡 Remember: Nested ifs are powerful but easy to overuse. Always ask: "Can I express this with && instead?" If yes, that's usually cleaner code!Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript Nested If Statement Tutorial – Multi-Level Conditions with Examples.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, control, flow, nested
Related JavaScript Master Course Topics