JavaScript Conditional Statements Explained (if-else vs switch)”

If-Else & Switch Case in JavaScript — Complete Guide with Examples (2026)
πŸ”€ Conditional Statements · Complete Guide

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.

⏱️ 10 min read πŸ”€ All Conditions πŸ’» Real Examples ⚠️ Common Mistakes

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.

if

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 + "!");

}
▶ Output
πŸ”₯ It's very hot today! ✅ Withdrawal successful. Balance: 2000 πŸŽ‰ Entry allowed! Welcome, Sara!
if/else

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
▶ Output
✅ You PASSED! A+ — Outstanding! πŸ† B — Good! πŸ‘ F — Failed. πŸ˜” Free! 🎁 Adult: Rs.500 Senior: Rs.250
switch

Switch 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");

}
▶ Output
😩 Start of the work week 2. Edit Profile ✏️ 28 or 29 days
&&

Nested 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");

}
▶ Output
Age check passed ✅ Ticket check passed ✅ 🎫 Regular Entrance 🎯 Eligible for promotion! πŸ–️ Day off! πŸ” Please log in to continue
πŸ’‘ Avoid deep nesting: If your conditions are nested more than 3 levels deep, your code becomes very hard to read. Instead, use early return — check the negative condition first and return early to avoid nesting.
vs

if-else vs switch — When to Use Which?

Featureif-elseswitch
Best forRange checks (age > 18, score < 50)Exact value matching (day === "Monday")
Condition typeAny boolean expressionSingle value equality only
Multiple casesWorks but gets longClean and readable
Defaultelse blockdefault: case
Fall-throughNot possiblePossible (needs break)
⚠️

Common Mistakes in Conditional Statements

❌ Mistake 1 — Using = instead of ===
if (x = 5) — This ASSIGNS 5 to x (always true!)
if (x === 5) — This COMPARES x to 5 ✅
❌ Mistake 2 — Missing break in switch
case "A": console.log("A"); // no break — falls into case B!
case "A": console.log("A"); break; // stops correctly ✅
❌ Mistake 3 — Using == instead of ===
if ("5" == 5) → true (type coercion — unexpected!)
if ("5" === 5) → false (strict — correct!) ✅
✅ Optimization — Early Return Pattern
// 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

Q1: Write an if-else to check if a number is positive, negative, or zero
if(n > 0) "positive" else if(n < 0) "negative" else "zero"
Q2: What happens in switch when you forget break?
Fall-through — all cases below run until a break or end of switch
Q3: What does the default case in switch do?
Runs when no case matches — like the else in if-else
Q4: What is the difference between = and === in an if condition?
= assigns a value (bug!), === strictly compares value AND type
Q5: Write a condition: user must be 18+ AND have a valid ID
if (age >= 18 && hasID === true) { ... }

✅ Complete Summary — If-Else & Switch in JavaScript

🟣 if statement: Runs code only when condition is true — foundation of all decisions
πŸ”΅ 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.
πŸ“Œ Important Note

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