JavaScript Notes
Master JavaScript if-else, else-if ladder, nested conditions, ternary operator, and conditional best practices with detailed code examples and outputs.
What is the If-Else Statement?
The if-else statement extends the basic if statement by providing an alternative code block that executes when the condition is false. While a simple if either does something or does nothing, if-else always does one of two things — it provides two distinct paths of execution.
Think of it as a fork in the road: the condition determines which path your program takes, but it will always take exactly one path.
Syntax
Basic If-Else
if (condition) {
// Executes when condition is TRUE
} else {
// Executes when condition is FALSE
}Else-If Ladder
if (condition1) {
// Executes when condition1 is TRUE
} else if (condition2) {
// Executes when condition1 is FALSE and condition2 is TRUE
} else if (condition3) {
// Executes when both above are FALSE and condition3 is TRUE
} else {
// Executes when ALL conditions above are FALSE
}Visual Diagram: If-Else Flow
Basic If-Else Examples
Example 1: Even or Odd
let number = 7;
if (number % 2 === 0) {
console.log(`${number} is even`);
} else {
console.log(`${number} is odd`);
}7 is odd
Example 2: Age Verification
let age = 16;
if (age >= 18) {
console.log("You are an adult");
console.log("You can vote");
} else {
console.log("You are a minor");
console.log(`Wait ${18 - age} more years to vote`);
}You are a minor Wait 2 more years to vote
Example 3: Login Check
Incorrect password! Please try again
Else-If Ladder (Multiple Conditions)
The else-if ladder checks conditions from top to bottom and executes the first block whose condition is true. Once a match is found, all remaining conditions are skipped.
Example 1: Grade Calculator
let score = 78;
let grade;
if (score >= 90) {
grade = "A+";
} else if (score >= 80) {
grade = "A";
} else if (score >= 70) {
grade = "B";
} else if (score >= 60) {
grade = "C";
} else if (score >= 50) {
grade = "D";
} else {
grade = "F";
}
console.log(`Score: ${score}`);
console.log(`Grade: ${grade}`);Score: 78 Grade: B
Example 2: Temperature Classifier
let temp = 35;
if (temp >= 40) {
console.log("Extreme heat - stay indoors!");
} else if (temp >= 30) {
console.log("Hot day - stay hydrated");
} else if (temp >= 20) {
console.log("Pleasant weather");
} else if (temp >= 10) {
console.log("Cool - wear a jacket");
} else if (temp >= 0) {
console.log("Cold - bundle up!");
} else {
console.log("Freezing - dangerous conditions!");
}Hot day - stay hydrated
Example 3: HTTP Status Code Handler
let statusCode = 404;
if (statusCode >= 200 && statusCode < 300) {
console.log("Success! Request completed");
} else if (statusCode >= 300 && statusCode < 400) {
console.log("Redirect - resource moved");
} else if (statusCode >= 400 && statusCode < 500) {
console.log("Client error - check your request");
} else if (statusCode >= 500) {
console.log("Server error - try again later");
} else {
console.log("Unknown status code");
}Client error - check your request
How the Else-If Ladder Works Internally
let x = 15;
if (x > 20) {
console.log("Greater than 20"); // Check 1: 15 > 20? NO → skip
} else if (x > 10) {
console.log("Greater than 10"); // Check 2: 15 > 10? YES → execute
} else if (x > 5) {
console.log("Greater than 5"); // NEVER REACHED (previous matched)
} else {
console.log("5 or less"); // NEVER REACHED
}Greater than 10
Key Point: Even though x > 5 is also true, it's never checked because x > 10 matched first. Order matters!
Nested If-Else Statements
let user = "admin";
let isLoggedIn = true;
let hasTwoFactor = true;
if (isLoggedIn) {
if (user === "admin") {
if (hasTwoFactor) {
console.log("Full admin access granted");
} else {
console.log("Please enable 2FA for admin access");
}
} else {
console.log("Standard user access");
}
} else {
console.log("Please log in first");
}Full admin access granted
Flattening Nested If-Else (Better Approach)
let user2 = "admin";
let isLoggedIn2 = true;
let hasTwoFactor2 = true;
if (!isLoggedIn2) {
console.log("Please log in first");
} else if (user2 !== "admin") {
console.log("Standard user access");
} else if (!hasTwoFactor2) {
console.log("Please enable 2FA for admin access");
} else {
console.log("Full admin access granted");
}Full admin access granted
If-Else with Complex Conditions
Combining AND and OR
Entry allowed
Multiple Criteria Validation
All validations passed! Welcome, john_doe!
Ternary Operator – Shorthand If-Else
The ternary operator ? : is a concise way to write simple if-else statements that assign values.
// Syntax: condition ? valueIfTrue : valueIfFalse
let age3 = 20;
let status = age3 >= 18 ? "Adult" : "Minor";
console.log(status);
let score2 = 45;
let result = score2 >= 50 ? "Pass" : "Fail";
console.log(result);
let hour = 14;
let greeting = hour < 12 ? "Good Morning" : "Good Afternoon";
console.log(greeting);Adult Fail Good Afternoon
Nested Ternary (Use Sparingly)
let marks = 78;
let grade2 = marks >= 90 ? "A+" :
marks >= 80 ? "A" :
marks >= 70 ? "B" :
marks >= 60 ? "C" : "F";
console.log(`Marks: ${marks}, Grade: ${grade2}`);Marks: 78, Grade: B
Warning: Nested ternaries hurt readability. Use else-if for complex logic.
If-Else with Return Statements (Functions)
function getDiscount(amount, memberType) {
if (memberType === "gold") {
return amount * 0.20;
} else if (memberType === "silver") {
return amount * 0.15;
} else if (memberType === "bronze") {
return amount * 0.10;
} else {
return 0;
}
}
console.log("Gold discount:", getDiscount(1000, "gold"));
console.log("Silver discount:", getDiscount(1000, "silver"));
console.log("Regular discount:", getDiscount(1000, "regular"));Gold discount: 200 Silver discount: 150 Regular discount: 0
Early Return Pattern
Error: No order provided Error: Cart is empty Order placed! 1 items confirmed
Real-World Examples
BMI Calculator
function calculateBMI(weight, height) {
let bmi = weight / (height * height);
let category;
if (bmi < 18.5) {
category = "Underweight";
} else if (bmi < 25) {
category = "Normal weight";
} else if (bmi < 30) {
category = "Overweight";
} else {
category = "Obese";
}
console.log(`BMI: ${bmi.toFixed(1)} - ${category}`);
}
calculateBMI(70, 1.75);
calculateBMI(55, 1.70);
calculateBMI(95, 1.80);BMI: 22.9 - Normal weight BMI: 19.0 - Normal weight BMI: 29.3 - Overweight
Shopping Cart Discount
function applyDiscount(cartTotal, couponCode) {
let discount = 0;
let message = "";
if (couponCode === "SAVE50" && cartTotal >= 500) {
discount = 50;
message = "₹50 flat discount applied!";
} else if (couponCode === "TWENTY" && cartTotal >= 1000) {
discount = cartTotal * 0.20;
message = "20% discount applied!";
} else if (cartTotal >= 2000) {
discount = cartTotal * 0.10;
message = "Auto 10% discount for orders above ₹2000";
} else {
message = "No discount applicable";
}
console.log(`Cart: ₹${cartTotal}`);
console.log(message);
console.log(`Final: ₹${cartTotal - discount}`);
console.log("---");
}
applyDiscount(1500, "TWENTY");
applyDiscount(600, "SAVE50");
applyDiscount(3000, "NONE");Cart: ₹1500 20% discount applied! Final: ₹1200 --- Cart: ₹600 ₹50 flat discount applied! Final: ₹550 --- Cart: ₹3000 Auto 10% discount for orders above ₹2000 Final: ₹2700 ---
Day Planner
let currentHour = 14;
let activity;
if (currentHour >= 5 && currentHour < 8) {
activity = "Morning exercise";
} else if (currentHour >= 8 && currentHour < 12) {
activity = "Work - deep focus time";
} else if (currentHour >= 12 && currentHour < 13) {
activity = "Lunch break";
} else if (currentHour >= 13 && currentHour < 17) {
activity = "Work - meetings & collaboration";
} else if (currentHour >= 17 && currentHour < 20) {
activity = "Personal time";
} else {
activity = "Rest & sleep";
}
console.log(`Time: ${currentHour}:00`);
console.log(`Suggested: ${activity}`);Time: 14:00 Suggested: Work - meetings & collaboration
❌ Common Mistakes
Mistake 1: Missing Else — Silent Bugs
let input = -5;
// ❌ BAD: Doesn't handle negative numbers
if (input > 0) {
console.log("Positive");
} else if (input === 0) {
console.log("Zero");
}
// Negative numbers: complete silence! Bug!
// ✅ GOOD: Always have a final else
if (input > 0) {
console.log("Positive");
} else if (input === 0) {
console.log("Zero");
} else {
console.log("Negative ✓");
}Negative ✓
Mistake 2: Overlapping Conditions — Wrong Order
let score3 = 85;
// ❌ BAD: More general condition checked first
if (score3 >= 50) {
console.log("Pass (but 85 should be Distinction!)");
} else if (score3 >= 80) {
console.log("Distinction"); // Never reached for 85!
}
// ✅ GOOD: Check from most specific to least specific
if (score3 >= 80) {
console.log("Distinction ✓");
} else if (score3 >= 50) {
console.log("Pass");
} else {
console.log("Fail");
}Pass (but 85 should be Distinction!) Distinction ✓
Mistake 3: Using Multiple Ifs When Else-If is Needed
let day = "Monday";
// ❌ BAD: Multiple independent ifs check all conditions
if (day === "Monday") console.log("Start of week");
if (day === "Friday") console.log("End of week");
if (day === "Saturday") console.log("Weekend");
// All conditions checked regardless
// ✅ GOOD: else-if stops at first match
if (day === "Monday") {
console.log("Start of week ✓");
} else if (day === "Friday") {
console.log("End of week");
} else if (day === "Saturday") {
console.log("Weekend");
}Start of week Start of week ✓
🎤 Interview Questions
Q1. What is the difference between if-else and multiple if statements? > Multiple if statements check ALL conditions independently. if-else-if stops at the FIRST true condition. Use if-else-if when conditions are mutually exclusive or when only one should run.
Q2. Can the else block exist without an if block? > No. else must always follow an if or else if block. A standalone else is a syntax error.
Q3. What is the "dangling else" problem? > When nested if statements exist without braces, it's ambiguous which if an else belongs to. In JavaScript, else always binds to the nearest preceding unmatched if. Always use braces to avoid this.
Q4. What is the ternary operator and when should you use it? > condition ? valueIfTrue : valueIfFalse — a shorthand for simple if-else that returns a value. Use it for simple one-liner value assignments. Avoid for complex logic as it hurts readability.
Q5. What happens when no condition in else-if is true and there's no else? > The program simply continues execution after the if-else block. No error occurs. This can be a silent bug if all cases should be handled.
Q6. What is the output?
let a = 10, b = 20, c = 30;
if (a > b) {
console.log("a biggest");
} else if (b > c) {
console.log("b biggest");
} else {
console.log("c biggest");
}c biggest — a=10 is not > b=20, b=20 is not > c=30, so else runs.Q7. Why does condition order matter in else-if? > Conditions are checked top-to-bottom. The first true condition runs, and the rest are skipped. If a general condition (like score >= 50) comes before a specific one (like score >= 90), the specific case is never reached for overlapping values.
Q8. What is early return / guard clause pattern? > Place if-statements at the start of a function to return early for invalid/edge cases, keeping the main logic flat and readable: if (!user) return "error"; // main logic here...
🔑 Key Takeaways
| Concept | Detail |
|---|---|
| if-else | Always executes one of two paths |
| else-if ladder | Checks top-to-bottom, first match wins |
| Order matters | Most specific conditions must come first |
| Ternary operator | Shorthand for simple value assignments |
| Always have else | Prevents silent bugs for unhandled cases |
| Early return | Flattens deeply nested if-else chains |
💡 Remember: In an else-if ladder, order is everything! Always put the most specific conditions first, and always end with an else to catch unexpected cases.Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript If Else Statement Tutorial – Complete Guide 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, else
Related JavaScript Master Course Topics