JavaScript Conditionals Explained — if, else, and switch with Real Examples
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.
// 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.");
Current health: 45
Game loop continues...
Second player check complete.
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.
// 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."); }
--- Bonus Score Check ---
Passed! (Matched the >= 70 condition)
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.
// 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
Ternary discount: 20%
Welcome, Premium Member! Your total after discount: $96
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.
// 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."); }
--- Warm Drink Prep ---
Adding chocolate syrup to mocha.
| Feature | if / else if / else | switch | Ternary Operator |
|---|---|---|---|
| Best used when | Conditions involve ranges or complex logic (e.g. score > 90) | Checking one value against many exact fixed values | Simple two-outcome assignments or expressions |
| Readability with 2 outcomes | Clear and readable | Overkill — too verbose | Very clean and concise |
| Readability with 5+ outcomes | Gets messy with many else if blocks | Clean and easy to scan | Avoid — becomes unreadable |
| Can compare ranges | Yes (e.g. age >= 18) | No — only exact matches | Yes, but gets messy quickly |
| Returns a value directly | No — it's a statement | No — it's a statement | Yes — it's an expression |
| Fall-through behaviour | Not possible | Yes — intentional or accidental | Not applicable |
| Performance on many cases | Checks top to bottom sequentially | Jumps 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.
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.