JavaScript Conditional Statements Explained (if-else vs switch)”
If-Else & Switch Case
in JavaScript
Master all JavaScript conditional statements — if, if-else, else if ladder, switch case, nested conditions, logical operators, real examples, common mistakes, and optimization tips.
What Are Conditional Statements in JavaScript?
Conditional statements are the decision-making tools of JavaScript. They allow your program to make choices — execute different blocks of code depending on whether a condition is true or false. Without conditional statements, your code would always do the same thing regardless of the situation — it would have no intelligence.
Think of conditional statements like the decisions you make every day. "If it's raining, take an umbrella — otherwise, leave it at home." "If your score is above 50, you pass — else, you fail." These are real-life conditions, and JavaScript lets you express them in code.
JavaScript has several types of conditional statements: the if statement, if-else, the else if ladder for multiple conditions, and the switch case for matching a value against multiple specific options. Each one has its place and understanding when to use which one makes your code much cleaner and more efficient.
The if Statement — The Foundation of All Decisions
The if statement is the simplest conditional. It checks a condition — if the condition is true, the code inside the block runs. If it is false, the block is skipped entirely. This is the building block for all decision-making in JavaScript.
let temperature = 38; // Basic if — runs only when condition is true if (temperature > 35) { console.log("π₯ It's very hot today!"); } let balance = 5000; let withdrawal = 3000; if (balance >= withdrawal) { balance -= withdrawal; console.log("✅ Withdrawal successful. Balance: " + balance); } // if with multiple conditions using && and || let age = 20; let hasID = true; if (age >= 18 && hasID) { console.log("π Entry allowed!"); } // Truthy/Falsy values — JavaScript evaluates these as false: // 0, "", null, undefined, NaN, false let userName = "Sara"; if (userName) { // non-empty string is truthy console.log("Welcome, " + userName + "!"); }
π₯ It's very hot today!
✅ Withdrawal successful. Balance: 2000
π Entry allowed!
Welcome, Sara!if-else & else if Ladder — Handling Multiple Conditions
The if-else gives your program two paths — when the condition is true, do one thing; otherwise, do something else. The else if ladder allows you to check multiple conditions one by one — JavaScript checks each condition from top to bottom and runs the first one that is true, then skips all the rest.
// if-else — two paths let score = 67; if (score >= 50) { console.log("✅ You PASSED!"); } else { console.log("❌ You FAILED. Try again!"); } // else if ladder — multiple conditions checked in order function getGrade(score) { if (score >= 90) { return "A+ — Outstanding! π"; } else if (score >= 80) { return "A — Excellent! ⭐"; } else if (score >= 70) { return "B — Good! π"; } else if (score >= 60) { return "C — Average. π"; } else if (score >= 50) { return "D — Passed. π"; } else { return "F — Failed. π Study harder!"; } } console.log(getGrade(95)); // A+ — Outstanding! π console.log(getGrade(72)); // B — Good! π console.log(getGrade(45)); // F — Failed. π Study harder! // Real-life example — ticket pricing function getTicketPrice(age) { if (age < 5) return "Free! π"; else if (age < 18) return "Child: Rs.200"; else if (age < 60) return "Adult: Rs.500"; else return "Senior: Rs.250"; } console.log(getTicketPrice(3)); // Free! π console.log(getTicketPrice(25)); // Adult: Rs.500 console.log(getTicketPrice(65)); // Senior: Rs.250
✅ You PASSED!
A+ — Outstanding! π B — Good! π F — Failed. π
Free! π Adult: Rs.500 Senior: Rs.250Switch Case — Matching One Value Against Many Options
The switch statement is perfect when you need to compare one variable against many specific values. Instead of writing many else if statements all checking the same variable, switch is cleaner and often easier to read. Each case is a possible value to match, and break is crucial — without it, JavaScript continues running into the next case (called "fall-through").
// Basic switch statement let day = "Monday"; switch (day) { case "Monday": console.log("π© Start of the work week"); break; case "Friday": console.log("π TGIF! Almost weekend!"); break; case "Saturday": case "Sunday": // Multiple cases, same result console.log("π️ Weekend! Relax!"); break; default: // Runs if no case matches console.log("π Regular weekday"); } // Switch with numbers — menu system let choice = 2; switch (choice) { case 1: console.log("1. View Profile"); break; case 2: console.log("2. Edit Profile ✏️"); break; case 3: console.log("3. Delete Account"); break; default: console.log("Invalid choice!"); } // Fall-through (no break) — intentional cascade let month = 2; switch (month) { case 1: case 3: case 5: console.log("31 days"); break; case 2: console.log("28 or 29 days"); break; default: console.log("30 days"); }
π© Start of the work week
2. Edit Profile ✏️
28 or 29 daysNested Conditions & Logical Operators in Conditions
Nested conditions are if statements placed inside other if statements. They are used when you need to check secondary conditions after a first condition passes. Logical operators (&&, ||, !) let you combine multiple conditions in a single line — making complex logic more concise.
// Nested if — check inside a check let age = 20; let hasTicket = true; let isVIP = false; if (age >= 18) { console.log("Age check passed ✅"); if (hasTicket) { console.log("Ticket check passed ✅"); if (isVIP) { console.log("π VIP Entrance — Front Row!"); } else { console.log("π« Regular Entrance"); } } else { console.log("❌ No ticket — cannot enter"); } } else { console.log("❌ Under 18 — not allowed"); } // Logical operators — combine conditions in one line let salary = 60000; let experience = 3; let hasSkill = true; // AND — all conditions must be true if (salary > 50000 && experience >= 2 && hasSkill) { console.log("π― Eligible for promotion!"); } // OR — at least one must be true let isWeekend = false; let isHoliday = true; if (isWeekend || isHoliday) { console.log("π️ Day off!"); } // NOT — reverse the condition let isLoggedIn = false; if (!isLoggedIn) { console.log("π Please log in to continue"); }
Age check passed ✅
Ticket check passed ✅
π« Regular Entrance
π― Eligible for promotion!
π️ Day off!
π Please log in to continueif-else vs switch — When to Use Which?
| Feature | if-else | switch |
|---|---|---|
| Best for | Range checks (age > 18, score < 50) | Exact value matching (day === "Monday") |
| Condition type | Any boolean expression | Single value equality only |
| Multiple cases | Works but gets long | Clean and readable |
| Default | else block | default: case |
| Fall-through | Not possible | Possible (needs break) |
Common Mistakes in Conditional Statements
// Instead of deep nesting:
function processUser(user) {
if (!user) return "No user"; // exit early
if (!user.isActive) return "Inactive";
return "Welcome, " + user.name; // clean!
}
π️ Practice Questions
✅ Complete Summary — If-Else & Switch in JavaScript
π΅ if-else: Two paths — true block OR false block — one always runs
π’ else if ladder: Multiple conditions checked top to bottom — first true wins
π‘ switch case: Match one value against many options — always use break!
π Nested conditions: if inside if — for multi-level checks — avoid deep nesting
π©· Logical operators: && (AND), || (OR), ! (NOT) — combine conditions in one line
π΄ Common mistakes: = vs === · missing break in switch · too deep nesting
⭐ Use if-else for ranges/complex conditions. Use switch for exact value matching.
Conditional statements are the intelligence of your program. Without them, code is just a series of commands with no decision-making ability. Practice writing real-world conditions — a login system, a grade calculator, a restaurant menu, a shopping cart discount — anything that requires different behavior in different situations. The more real examples you write, the more natural conditionals will feel!
Comments
Post a Comment