Home JavaScript JavaScript Conditionals Explained — if, else, and switch with Real Examples

JavaScript Conditionals Explained — if, else, and switch with Real Examples

In Plain English 🔥
Imagine you're a bouncer at a club. You check someone's ID — if they're over 18, they get in; if not, they're turned away. That decision-making process is exactly what a conditional does in JavaScript. It lets your program ask a question, check whether the answer is true or false, and then choose what to do next. Without conditionals, your code would do the same thing every single time, no matter what — like a vending machine that gives you the same snack regardless of which button you press.
⚡ Quick Answer
Imagine you're a bouncer at a club. You check someone's ID — if they're over 18, they get in; if not, they're turned away. That decision-making process is exactly what a conditional does in JavaScript. It lets your program ask a question, check whether the answer is true or false, and then choose what to do next. Without conditionals, your code would do the same thing every single time, no matter what — like a vending machine that gives you the same snack regardless of which button you press.

Every useful program on the planet makes decisions. When you log into Netflix, the app checks whether your password is correct. When you add items to a shopping cart, the site checks whether you have enough credit. When a game character takes damage, the engine checks whether their health has hit zero. None of that is magic — it's all conditionals, and JavaScript gives you a clean, powerful way to write them.

Before conditionals existed in programming, code ran top-to-bottom like reading a book — line 1, line 2, line 3, done. That's fine for a calculator that always adds two numbers, but useless for anything interactive. Conditionals solve the 'what if?' problem. They let your code branch — choosing path A when something is true, and path B when it's not, just like a fork in a road.

By the end of this article you'll be able to write if/else statements, chain multiple conditions with else if, use the ternary operator as a shortcut, and pick the right tool with a switch statement. You'll also know the two most common mistakes beginners make — and exactly how to avoid them.

The if Statement — Teaching Your Code to Ask a Question

The if statement is the most fundamental conditional in JavaScript. Think of it as a gatekeeper. You hand it a question — technically called a condition — and it evaluates whether that condition is true or false. If it's true, the code inside the curly braces runs. If it's false, JavaScript skips the whole block entirely and moves on.

The condition always lives inside parentheses after the word if. That condition must evaluate to a boolean — meaning it must boil down to either true or false. You'll often see comparison operators here: == checks equality, > checks greater than, < checks less than, and so on.

One important detail: the curly braces {} are your 'block'. Everything inside them belongs to that if statement. Keep them — even when you only have one line of code inside. Skipping braces is technically allowed but causes bugs that are notoriously hard to find, and every senior dev has a horror story about it.

checkPlayerHealth.js · JAVASCRIPT
1234567891011121314151617181920212223242526
// A simple game scenario — checking if the player is still alive

const playerHealth = 45; // The player's current health points
const minimumHealth = 0; // Health at or below this means game over

// The 'if' keyword starts the conditional.
// The condition (playerHealth > minimumHealth) is evaluated — is 45 > 0? YES, so it's true.
// Because it's true, the code inside the curly braces runs.
if (playerHealth > minimumHealth) {
  console.log("Player is alive. Keep fighting!");
  // This line also runs because it's inside the same block
  console.log("Current health: " + playerHealth);
}

// This line is OUTSIDE the if block — it always runs, no matter what
console.log("Game loop continues...");

// Now let's see what happens when the condition is FALSE
const secondPlayerHealth = 0;

if (secondPlayerHealth > minimumHealth) {
  // 0 > 0 is FALSE — so JavaScript skips everything in here
  console.log("This will NOT print because the condition is false.");
}

console.log("Second player check complete.");
▶ Output
Player is alive. Keep fighting!
Current health: 45
Game loop continues...
Second player check complete.
⚠️
Watch Out: = vs == vs ===A single = is assignment (you're storing a value). A double == is a loose equality check. A triple === is a strict equality check — it checks both value AND type. Use === almost always. Writing if (score = 10) instead of if (score === 10) is one of the most common beginner bugs — it assigns 10 to score instead of comparing, and the condition always evaluates to true.

if / else and else if — Handling Multiple Outcomes

An if statement alone handles one outcome: 'do this IF the condition is true, otherwise do nothing.' But real programs almost always need to handle what happens when the condition is false too. That's where else comes in.

Think of else as the 'otherwise' clause in plain English. 'If the traffic light is green, drive — otherwise, stop.' The else block catches every case that wasn't true.

But what if you have more than two possible outcomes? What if a traffic light can be green, yellow, or red? That's where else if shines. You can chain as many else if blocks as you need, and JavaScript will evaluate them one by one from top to bottom, stopping as soon as it finds the first true condition. This 'top-down, first match wins' behaviour is critical to understand — order matters.

Always end an if / else if chain with a plain else as your safety net. It catches any case you didn't explicitly predict, which prevents silent failures in your code.

gradeCalculator.js · JAVASCRIPT
12345678910111213141516171819202122232425262728293031323334
// Converting a numeric exam score into a letter grade
// This is a perfect use case for if / else if / else — multiple distinct outcomes

const examScore = 74; // The student's score out of 100

if (examScore >= 90) {
  // Is 74 >= 90? No. JavaScript skips this block and checks the next condition.
  console.log("Grade: A — Excellent work!");
} else if (examScore >= 80) {
  // Is 74 >= 80? No. Skip and check next.
  console.log("Grade: B — Great job!");
} else if (examScore >= 70) {
  // Is 74 >= 70? YES. JavaScript runs this block and stops checking the rest.
  console.log("Grade: C — Good effort, room to grow.");
} else if (examScore >= 60) {
  // This never even gets evaluated because the block above already matched
  console.log("Grade: D — Consider reviewing the material.");
} else {
  // This is the safety net — catches any score below 60
  console.log("Grade: F — Please see your instructor.");
}

// Demonstrating the 'top-down, first match wins' rule
const bonusScore = 95;

console.log("\n--- Bonus Score Check ---");

if (bonusScore >= 70) {
  // Is 95 >= 70? YES — this matches FIRST, so everything below is ignored
  console.log("Passed! (Matched the >= 70 condition)");
} else if (bonusScore >= 90) {
  // This would also be true, but JavaScript never gets here
  console.log("This will NEVER print, even though 95 >= 90 is true.");
}
▶ Output
Grade: C — Good effort, room to grow.

--- Bonus Score Check ---
Passed! (Matched the >= 70 condition)
⚠️
Pro Tip: Order Your Conditions from Most Specific to Least SpecificAlways write your most restrictive condition first. In the grade example, >= 90 comes before >= 70 — because 90 also satisfies >= 70. If you flipped them, every score above 70 would match the first condition and the A grade would never be reachable. This is the single most common logic bug in if/else if chains.

The Ternary Operator — A One-Line Shortcut for Simple Choices

Sometimes your if/else logic is so simple — 'if this is true, use value A, otherwise use value B' — that writing four lines of code for it feels like overkill. JavaScript gives you the ternary operator as a concise alternative for exactly these situations.

The word 'ternary' just means it takes three parts: the condition, the value if true, and the value if false. The syntax is: condition ? valueIfTrue : valueIfFalse. Read the ? as 'then' and the : as 'otherwise', and it reads almost like plain English.

The ternary operator is especially powerful when you're assigning a value to a variable based on a condition, or when you're embedding a decision directly inside a string or function call. However, resist the urge to chain multiple ternary operators together — it becomes unreadable fast. If your logic has more than two outcomes, stick with if/else if. Ternary is a scalpel, not a Swiss Army knife.

membershipDiscount.js · JAVASCRIPT
123456789101112131415161718192021222324252627282930
// Scenario: An e-commerce site applies a discount for premium members

const isPremiumMember = true; // Whether the user has a paid membership
const cartTotal = 120;        // The total cost of items in the cart

// THE LONG WAY using if/else
let discountPercentageLong;
if (isPremiumMember) {
  discountPercentageLong = 20; // 20% off for premium members
} else {
  discountPercentageLong = 5;  // 5% off for everyone else
}
console.log("Long way discount: " + discountPercentageLong + "%");

// THE SHORT WAY using the ternary operator
// Read as: 'isPremiumMember? Then 20, Otherwise 5'
const discountPercentage = isPremiumMember ? 20 : 5;
console.log("Ternary discount: " + discountPercentage + "%");

// Ternary is great for embedding decisions directly in a string
const discountedTotal = cartTotal - (cartTotal * discountPercentage / 100);
console.log(
  "Welcome, " + (isPremiumMember ? "Premium Member" : "Guest") +
  "! Your total after discount: $" + discountedTotal
);

// Example of what NOT to do — nested ternaries are hard to read
// Don't write this:
// const label = score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'F';
// Use if/else if instead when you have more than 2 outcomes
▶ Output
Long way discount: 20%
Ternary discount: 20%
Welcome, Premium Member! Your total after discount: $96
🔥
Interview Gold: Why Use Ternary Over if/else?Interviewers love asking this. The right answer isn't 'because it's shorter' — it's 'because a ternary is an expression that produces a value, while an if/else is a statement that doesn't.' That means you can use a ternary directly inside a variable assignment, a function argument, or a template literal. You can't do that with an if/else block.

The switch Statement — Clean Multi-Way Branching

Imagine you're writing code to handle the day of the week — seven possible values, seven different outcomes. You could write seven else if blocks, but it would look like a wall of repeated code. The switch statement is built for exactly this scenario: when you're checking one variable against many specific, fixed values.

Switch takes a single expression, evaluates it once, then jumps directly to the case that matches it. It's faster to read and much cleaner when you have four or more possible values to check against. Each case ends with a break statement — this is JavaScript's signal to stop executing and jump out of the switch block.

If you forget break, JavaScript will 'fall through' — it'll keep running every case below the matching one until it hits a break or the end of the switch. This is a notorious source of bugs for beginners but is occasionally used intentionally by experienced developers when multiple cases should share the same logic. The default case at the bottom is like else — it catches anything that didn't match.

coffeeOrderRouter.js · JAVASCRIPT
123456789101112131415161718192021222324252627282930313233343536373839404142434445
// A coffee shop order system — routing to the correct preparation method
// Perfect use of switch: one variable, multiple specific values to check

const customerOrder = "latte"; // The drink the customer ordered

switch (customerOrder) {
  case "espresso":
    // Does customerOrder === 'espresso'? No. Skip.
    console.log("Pulling a double shot of espresso.");
    break; // Stop here — don't run any other cases

  case "latte":
    // Does customerOrder === 'latte'? YES. Run this block.
    console.log("Pulling espresso shot and steaming milk for a latte.");
    break; // Without this 'break', JavaScript would fall through to 'cappuccino'!

  case "cappuccino":
    console.log("Pulling espresso shot and adding thick foam for a cappuccino.");
    break;

  case "americano":
    console.log("Pulling espresso shot and adding hot water.");
    break;

  default:
    // Catches anything that didn't match any case above
    console.log("Sorry, we don't have '" + customerOrder + "' on the menu.");
    break; // Good habit to include break in default too
}

// INTENTIONAL FALL-THROUGH — multiple cases sharing the same logic
// Both 'mocha' and 'hot chocolate' need the chocolate syrup step
const warmDrink = "mocha";

console.log("\n--- Warm Drink Prep ---");

switch (warmDrink) {
  case "mocha":
    // No break here — falls through to 'hot chocolate' on purpose
  case "hot chocolate":
    console.log("Adding chocolate syrup to " + warmDrink + ".");
    break;
  default:
    console.log("No chocolate needed for this drink.");
}
▶ Output
Pulling espresso shot and steaming milk for a latte.

--- Warm Drink Prep ---
Adding chocolate syrup to mocha.
⚠️
Watch Out: switch Uses Strict Equality (===)Switch compares cases using strict equality — it checks both value and type. So if your variable holds the number 1 and your case says case '1':, it will NOT match because one is a number and the other is a string. Always make sure the type of your switch expression matches the type in your case labels.
Featureif / else if / elseswitchTernary Operator
Best used whenConditions involve ranges or complex logic (e.g. score > 90)Checking one value against many exact fixed valuesSimple two-outcome assignments or expressions
Readability with 2 outcomesClear and readableOverkill — too verboseVery clean and concise
Readability with 5+ outcomesGets messy with many else if blocksClean and easy to scanAvoid — becomes unreadable
Can compare rangesYes (e.g. age >= 18)No — only exact matchesYes, but gets messy quickly
Returns a value directlyNo — it's a statementNo — it's a statementYes — it's an expression
Fall-through behaviourNot possibleYes — intentional or accidentalNot applicable
Performance on many casesChecks top to bottom sequentiallyJumps directly to match (faster)Single evaluation — very fast

🎯 Key Takeaways

  • A conditional lets your code make a decision — it evaluates a condition to true or false and runs different code depending on the result.
  • Order your else if conditions from most specific to least specific — JavaScript stops at the first match, so a general condition placed too early will shadow the specific ones below it.
  • The ternary operator (condition ? valueA : valueB) is an expression that produces a value, which means you can use it inside assignments and function calls — unlike an if/else statement, which cannot.
  • Always use break in switch cases unless you intentionally want fall-through — missing a single break is one of the hardest bugs to spot because the code looks correct at a glance.

⚠ Common Mistakes to Avoid

  • Mistake 1: Using = (assignment) instead of === (strict equality) inside a condition — Symptom: The condition always evaluates to true and your else block never runs. For example, if (userAge = 18) sets userAge to 18 and then truthy-evaluates to true regardless of what userAge was — Fix: Always use === for comparison inside if conditions. Your linter (ESLint) will also catch this if you have one set up.
  • Mistake 2: Forgetting break in a switch statement — Symptom: Code falls through and runs multiple case blocks unintentionally. For example if you match 'latte' but forget break, it'll also run the 'cappuccino' block immediately after — Fix: Make it a habit to write the break statement at the same time you write the case, before you fill in the logic. Review every case before you run your switch block.
  • Mistake 3: Putting the most general else if condition first — Symptom: Your specific cases are unreachable — they technically match but the general condition above them always matches first. For example, if you write if (score >= 60) before if (score >= 90), a score of 95 will match the >= 60 case and you'll never reach the A-grade logic — Fix: Always order else if chains from most restrictive (highest threshold) to least restrictive (lowest threshold).

Interview Questions on This Topic

  • QWhat is the difference between == and === in a JavaScript conditional, and which should you use by default?
  • QWhen would you choose a switch statement over an if/else if chain? What are the trade-offs?
  • QWhat does 'fall-through' mean in a switch statement — is it always a bug, or can it be used intentionally? Give an example of each.

Frequently Asked Questions

What is the difference between if/else and switch in JavaScript?

An if/else chain is best when your conditions involve ranges or complex logic like 'is the score greater than 90?'. A switch statement is best when you're checking one single variable against a list of exact fixed values like specific strings or numbers. Switch is cleaner and easier to read when you have four or more specific values to match against.

Can you use a ternary operator instead of an if/else statement in JavaScript?

Yes, but only for simple two-outcome decisions. The ternary operator (condition ? valueIfTrue : valueIfFalse) is an expression that returns a value, making it ideal for variable assignments and inline use. For anything with more than two outcomes, or when you need to run multiple lines of code per branch, stick with if/else if for readability.

Why does my if statement always run even when the condition should be false?

The most likely cause is using a single = instead of === inside your condition. Writing if (score = 100) doesn't compare score to 100 — it assigns 100 to score, and since 100 is a truthy value, the condition always evaluates to true. Change it to if (score === 100) to compare the value instead of assigning it.

🔥
TheCodeForge Editorial Team Verified Author

Written and reviewed by senior developers with real-world experience across enterprise, startup and open-source projects. Every article on TheCodeForge is written to be clear, accurate and genuinely useful — not just SEO filler.

← PreviousLoops in JavaScriptNext →Type Coercion in JavaScript
Forged with 🔥 at TheCodeForge.io — Where Developers Are Forged