Back to Explore
GuideVibeFix editorialUpdated Nov 21, 2026

Decide first, code second: JavaScript conditionals — if, switch, and the ternary operator, explained plainly

Every web page makes decisions all day: a total over 100 gets a discount, zero stock shows sold out. Following MDN's Making decisions in your code — conditionals, if...else, and switch: if and else if, comparison operators, truthy and falsy, logical operators, the classic || mistake, nested if and the dangling else, switch and fall-through, the ternary operator, and guard clauses.

Real photo: a woman seen from behind reading a large chalkboard coffee menu listing espresso drinks, specials, and extras, with a pastry display case beside the counter

First, the boundaries of this guide. The site already has plenty of JavaScript basics guides: the functions guide covers how to write functions, array methods covers lists, string methods covers text, numbers and Math covers arithmetic, regex covers patterns, and objects and destructuring, classes and prototypes, closures, the event loop, modules, Fetch, DOM, and localStorage each have their own guide. This one does not repeat them. It covers one thing only: conditionals. When you build a web page you make decisions all day: an order over 100 gets a discount, stock of zero shows sold out, a sunny day shows the beach suggestion. The example here is the same fictional practice project as before: Greenstone Cafe, a small order page for a street-side coffee shop. Earlier guides used it to explain functions and storage; this time it shows how an order page makes decisions: how much discount at which total, what message to show at each order step, and when the shop opens and closes. Every operation, code sample, and number using it is invented to explain the idea, not a real record. All syntax and behavior of conditionals comes from three MDN official docs: Making decisions in your code — conditionals, if...else, and switch. Sources are in each article's meta info and evidence record. After reading this guide, you should be able to do four things: write if, else if, and else; combine conditions with comparison and logical operators; know when a switch fits better than a long else if chain; and know when to use the ternary operator and guard clauses. This guide does not cover condition combinations inside loops in depth, and it does not cover the full rules of type conversion — it only explains the == trap thoroughly, then stops.

Step 1: A condition is "if this, do that; otherwise, do the other thing"

The MDN Learn article opens with a reassuring fact: conditionals are just everyday decisions written as code. A person decides whether to eat one cookie or two; code decides whether to run this block when a condition holds, or that block when it does not. The most common form is if...else: if (condition) holds the code that runs when the condition is true, and else holds the code that runs when it is not. The parentheses hold a condition with only two possible results: true or false. The braces can hold any code, and it only runs when the condition is true; the code after else only runs when the condition is false. MDN's example is very down to earth: a child is asked to help with the shopping, shoppingDone is false, and childAllowance starts out unassigned. If (shoppingDone === true), the child gets 10 in allowance; otherwise 5. shoppingDone is false, so the condition fails and the answer is 5. Verified: change shoppingDone to true and the answer becomes 10; call it with no argument and shoppingDone is undefined, undefined is not equal to true, so the answer is still 5. Two more things to remember: first, else is optional — writing only if is legal, but then nothing happens when the condition fails, and the code after it still runs as normal, so do not mistake later code for code controlled by the if. Second, writing if without braces is legal too, for example if (condition) doSomething();, but MDN explicitly recommends against it, because once the code gets longer it is hard to tell which lines the if controls. On the cafe order page, conditionals are everywhere: an order total of 100 or more gets a discount, otherwise full price; stock above zero shows "Add to cart", zero shows "Sold out". The check for this step is simple: before writing a condition, say the decision out loud in one sentence — "if the total reaches 100, give 15% off, otherwise charge full price" — and once the sentence is clear, the code follows it.

Step 2: else if — when there are more than two choices, they queue up

if...else is enough for two outcomes, but an order page often has more than two choices: the weather can be sunny, rainy, snowing, or overcast, and an order can be waiting, making, ready, or done. That is when else if comes in, chaining extra choices between if and else. MDN's weather example works exactly like this: it takes the value of a select dropdown as choice; if (choice === "sunny") it shows the beach message, else if (choice === "rainy") it shows the umbrella message, else if (choice === "snowing") it shows staying home with hot chocolate, else if (choice === "overcast") it shows the grey-sky warning, and the final else clears the paragraph. Conditions are tested in order: the first one that holds runs its block, and all later else if branches are skipped, none of them tested again; only when none of them holds does the final else run. In MDN's example that final else is the safety net, handling the case where the user picks the empty "--Make a choice--" option again. Verified: choice "sunny" shows the beach text, "rainy" shows the umbrella text, and an empty string clears the paragraph. On the cafe order page, else if fits "tiers" best: a total of 100 or more gets 15% off, 50 or more gets 5% off, anything else is full price. Written as a discountRate function, 120 gives 0.85, 60 gives 0.95, and 30 gives 1; the boundary values check out too, 100 is exactly 0.85 and 50 is exactly 0.95. The easy mistake here is ordering: conditions must run from strict to loose, because a loose one placed first will block the strict one. If you write "total of 50 or more gets 5% off" first, a 120 order hits that branch and never reaches the 15% off branch. After writing an else if chain, test it with boundary values one by one — that is the cheapest check there is.

Step 3: Comparison operators — strict equality first, avoid == when you can

The most common thing inside a condition's parentheses is a comparison: is this value the same as that one, bigger, or smaller? MDN's conditionals article lists six comparison operators: === and !== test whether two values are identical or not identical, and less than, greater than, less than or equal to, and greater than or equal to test size. The trap beginners fall into most is the pair === and ==, which look alike. === is strict equality: it does no type conversion, and values of different types are simply not equal. == is loose equality: before comparing, it quietly converts the types to match. Verified: "5" == 5 is true, because == turns the string "5" into the number 5 before comparing; "5" === 5 is false, because a string and a number are different types. More alarming: 0 == "" is true, because the empty string is converted to the number 0, while 0 === "" is false. null == undefined is true, while null === undefined is false. That is why every serious JavaScript guide recommends only ===: the conversion rules of == need a whole table to predict, while the result of === is obvious at a glance. switch uses strict equality too, which step 9 will come back to. On the cafe order page, comparisons show up in three common places: first, testing an order status, writing code === "ready" in orderStatus — never code = "ready", because a single equals sign is assignment, not comparison, and the condition would always be true; second, testing whether stock is zero, stock === 0; third, testing whether a price is free, price === 0 shows "Free". The check for this step: when writing a condition, ask whether both sides have the same type. If not, make the types match first, and do not count on == to guess for you.

Step 4: Truthy and falsy — you do not need to write === true

A condition's parentheses do not have to hold a comparison. MDN states it plainly: any value that is not false, undefined, null, 0, NaN, or an empty string counts as true when tested as a condition. So you can write if (cheese) instead of if (cheese === true). MDN's example is let cheese = "Cheddar"; if (cheese) prints "Yay! Cheese available for making cheese on toast", and changing cheese to an empty string takes the else branch. Verified: the string "Cheddar" is truthy, while the empty string, 0, NaN, null, undefined, and false are falsy. A few counterintuitive ones deserve their own note: the string "0" is truthy, because it is not an empty string — do not confuse it with the number 0; an empty array [] and an empty object {} are both truthy, because they are real objects, not nothing at all; the if...else reference adds two finer points, that -0 and 0n are also falsy, while new Boolean(false) is truthy, because it is an object even though the boolean value it wraps is false. Going back to the step 1 example, shoppingDone is already a boolean, so if (shoppingDone) works perfectly without if (shoppingDone === true) — MDN rewrites it exactly that way in the article, and it means the same thing while reading more cleanly. On the cafe order page, truthiness is most useful for "is there one": if (itemName) means "did the customer pick a drink", with an empty string taking the else branch; if (stock) means "is there stock left", with 0 taking the else branch. But be careful: a stock of 0 is falsy, and that is fine, yet if the number itself is what you want to display, do not use it as a condition for "is there one", or you will mistake a legitimate 0 for nothing. The check for this step: putting a variable name alone in a condition asks "does it exist and is it none of the six falsy values" — decide whether you are asking about existence or about equality with a specific value before you decide whether to write ===.

Step 5: Logical operators — combining several conditions into one

What if one condition is not enough? "Sunny and cooler than 86 degrees" is two conditions that must both hold before the beach is suggested. MDN's tool for that is logical operators, three of them: && is AND, both sides must be true for the whole thing to be true; || is OR, one side being true is enough; ! is NOT, turning true into false and false into true. MDN rewrites the nested weather example with &&: if (choice === "sunny" && temperature < 86) shows the beach message only when both hold; else if (choice === "sunny" && temperature >= 86) shows the warning to wear sunscreen in the heat. The || example is if (iceCreamVanOutside || houseStatus === "on fire"): the ice cream van arriving or the house being on fire are both reasons to leave the house quickly. The ! example negates the whole thing: if (!(iceCreamVanOutside || houseStatus === "on fire")) means stay inside when neither holds. All three can combine, as in MDN's example if ((x === 5 || y > 3 || z <= 10) && (loggedIn || userName === "Steve")). Verified: with x = 5, y = 0, z = 0, loggedIn = false, and userName = "Steve", the left group is already true because x === 5, the right group is true because userName is "Steve", so the whole condition is true. On the cafe order page, logical operators appear in three common places: first, opening hours, hour >= 8 && hour < 22 — 9 is open, 23 is closed, 7 is closed, 8 on the dot is open, 22 on the dot is closed, all verified; second, whether an order can be placed, item && stock > 0, where an empty name or zero stock both block the order; third, discount eligibility, total >= 100 || isMember, where members or orders over 100 both get the discount. The check for this step: before writing &&, ask whether both conditions are truly indispensable; before writing ||, ask whether satisfying one is enough. If the answers differ, you have picked the wrong operator.

Step 6: The classic || mistake — x === 5 || 7 is always true

This step covers one mistake on its own, because MDN calls it out by name and almost every beginner writes it once. To say "x equals 5, 7, 10, or 20", the instinctive code is if (x === 5 || 7 || 10 || 20). It looks right, but it is always true. MDN explains it plainly: each side of || must be a complete comparison, and 7 on its own is not a comparison — 7 is a non-zero number, which is always truthy in a condition, so the whole condition is always true no matter what x is. Verified: with x = 3 the wrong form is still true, while the correct form if (x === 5 || x === 7 || x === 10 || x === 20) is false; change x to 7 and the correct form becomes true. The correct form is just more repetitive: write x === again before every value. On the cafe order page, this mistake shows up most in "one of several" checks: to say "a latte, mocha, or cappuccino joins the promotion", writing if (drink === "latte" || "mocha" || "cappuccino") makes every drink join the promotion; the correct form is if (drink === "latte" || drink === "mocha" || drink === "cappuccino"). If the repetition bothers you, the includes method from the array methods guide can help: ["latte", "mocha", "cappuccino"].includes(drink) means the same thing and reads more cleanly — but that is an array method, and this guide only asks you to get the full || form right first. The check for this step: after writing a condition with ||, run it once with a value that definitely does not match. If the condition is still true, one side of your || is missing its comparison.

Step 7: Nested if and the dangling else — do not skip the braces

Putting one condition inside another is completely legal; MDN says each if...else works independently of the others. In the weather example you can nest a temperature check inside choice === "sunny": under 86 degrees suggests the beach, 86 or above warns about the heat. But nesting gets deep fast, and then a classic problem appears, called the dangling else: which if does an else belong to? The MDN if...else reference gives a textbook example: inside checkValue, if (a === 1) is directly followed by a nested if (b === 2), and then an else. It looks like the else belongs to the outer if, but it actually attaches to the nearest if, the inner one. Verified: checkValue(1, 3) logs "a is not 1", not the "a is 1 but b is not 2" you might have expected. MDN's conclusion is blunt: always use block statements, especially with nested ifs. Wrapping every if and else body in braces makes it obvious at a glance which else belongs to which if, no matter how messy the indentation gets. On the cafe order page, nesting most often looks like "big category first, detail second": first check whether the order is dine-in, then which table it sits at; first check whether the total reaches 100, then whether the customer is a member. My judgment is that once nesting passes two levels, it is time to stop and think: can the inner condition become its own function, or can a switch from the next step or a guard clause from step 11 flatten the structure? Nesting itself is not wrong, but three or more levels read like a tongue twister, and editing someone else's branch is where mistakes creep in. The check for this step: after writing nested code, point out which if each else belongs to, count that the braces pair up, then run one set of values where the inner and outer conditions disagree, and see whether the branch taken is the one you intended.

Step 8: switch — one value against many options

The weakness of if...else is that many choices make it wordy: ten options need ten else if branches, each repeating the variable name. MDN says a switch fits that case better: it takes a single expression as input and tries each case in turn, running the block of the first match. The form is switch (expression), with case choice1: running one block, break, case choice2: running another, break, and default: running the fallback. MDN rewrites the weather example as a switch: switch (choice), case "sunny" shows the beach text, case "rainy" shows the umbrella text, case "snowing" shows staying home, case "overcast" shows the grey-sky warning, and default clears the paragraph. MDN's fruit example is verified: with expr "Papayas", case "Mangoes" and case "Papayas" share one block, printing "Mangoes and papayas are $2.79 a pound."; with expr "Apples", no case matches, so default runs, printing "Sorry, we are out of Apples.". What makes switch better than an if...else chain? First, the variable name is written once, even with ten options. Second, all options lie flat together, so you can see the whole set at a glance. On the cafe order page, switch fits "one value, many fixed options" best: the order status code "waiting" shows "Waiting to be made", "making" shows "Being made", "ready" shows "Ready for pickup", "done" shows "Completed", and anything else falls to default, "Unknown status". Verified: "ready" gives "Ready for pickup", and an undefined code like "paid" falls to default. The check for this step: with two or three options and different conditions each, use if...else; with four or five options that all compare the same value, use switch.

Step 9: Two switch traps — a missing break falls through, and do not redeclare in a case

switch is handy, but it has two traps that if...else does not have, and MDN's switch reference spends a long section on them. The first is fall-through: once a case matches, execution keeps running downward until it hits a break or the end of the switch, even through cases that do not match. MDN's example is verified: with foo = 0, case 0 logs 0, the missing break lets execution fall into case 1, which logs 1, and only then does a break stop it — the result is the two values 0 and 1. Fall-through is sometimes deliberate, as with "Mangoes" and "Papayas" sharing one block, where case "Mangoes" has no break and drops straight into the "Papayas" block; but more often it is a forgotten break causing a bug, so an order that is "waiting" ends up displaying the "making" and "ready" messages as well. MDN's multi-operation example shows the power of fall-through even more clearly: with foo = 1, execution starts at case 1 and concatenates downward to "Output: What Is Your Name?"; with foo = 0 it starts at case 0 and gives "Output: So What Is Your Name?"; with foo = 5 it gives "Output: !"; with foo = 9 nothing matches and default runs. The second trap is redeclaring a variable inside a case: writing const message in two cases throws a SyntaxError straight away, MDN says, because both cases share the same block scope, so message is declared twice. The fix is to wrap each case in its own braces, locking the declaration into its own block; MDN gives the corrected form, which runs and logs hello without error. On the cafe order page, the switch rules should be: write break after every case, unless you deliberately want to share a block — and then leave a comment saying so; if a case needs to declare a variable, add braces first. The check for this step: after writing a switch, read each case top to bottom and look for its exit. No break and no return means fall-through — ask yourself whether that is deliberate or forgotten.

Step 10: The ternary operator — use it when you only need to pick one value

Sometimes a condition is not there to run a long block of code, only to pick one of two values: a birthday gets a birthday greeting, otherwise a good-morning greeting. That takes four or five lines as if...else, and one line as a ternary: condition ? first value : second value — the value after the question mark when the condition holds, the value after the colon when it does not. MDN's example is const greeting = isBirthday ? "Happy birthday Mrs. Smith — we hope you have a great day!" : "Good morning Mrs. Smith.". Verified: isBirthday true gives the birthday line, false gives the good-morning line. The ternary is not only for assigning variables; it can also call functions directly. In MDN's theme chooser, a select value of black calls update("black", "white"), and anything else calls update("white", "black"). On the cafe order page, the ternary is handiest for "either-or wording": the priceLabel function reads price === 0 ? "Free" : price < 20 ? "Budget" : "Premium" — 0 is Free, 15 is Budget, 35 is Premium, all verified; the discountRate function reads total >= 100 ? 0.85 : total >= 50 ? 0.95 : 1, also a nested ternary. But note: do not nest it more than one level deep — two question marks and two colons squeezed into one line force the reader to stop and count brackets. My judgment is that the ternary is made for "pick one value", not for "run a piece of logic": put only a value, or a single function call, after the question mark and after the colon, and anything beyond that belongs back in if...else. The check for this step: read your ternary out loud — "if the total reaches 100, 15% off; otherwise if it reaches 50, 5% off; otherwise full price". If it reads smoothly in one breath, the nesting is still fine; if it twists your tongue, split it back into if...else.

Step 11: Guard clauses — block the bad cases at the door first

The previous ten steps all asked "what do we do when a condition holds". This step turns the habit around: check the bad inputs first, at the top of the function, and return right away, so the rest of the code never needs deep nesting. This habit is called a guard clause: a function starts by checking its inputs, returns immediately when one fails, and only then writes the normal flow. The clearest cafe example is the orderDrink function: first check whether the name is empty — if so, return "Please pick a drink first"; then check whether stock is zero — if so, return "Sold out"; only when both checks pass, return "Ordered: latte". Verified: an empty name gives "Please pick a drink first", the name "latte" with stock 0 gives "Sold out", and "latte" with stock 2 gives "Ordered: latte". Without guard clauses, the same logic needs if inside if inside else, with the normal flow buried at the deepest level, tiring to read. The two small checks alongside it fit the same pattern: canOrder returns true only when the name is non-empty and stock is above zero — an empty name returns false, stock 0 returns false; isOpen is hour >= 8 && hour < 22 — 9 is true, 23 and 7 are false. Guard clauses have another benefit: each check owns one failure, and the failure reason is written in the return value, so when debugging you can see at a glance which gate the input failed at. The check for this step: at the top of a function, ask which inputs should never go any further. Block them one by one, and what remains is a straight road with no more conditions wrapped around it.

Step 12: Pre-launch checklist and a chart of what went wrong

The chart below shows the breakdown of 100 fictional conditional mistakes in one month on the Greenstone Cafe order page. The numbers are invented examples, matched against the traps from the previous eleven steps: using = assignment instead of comparison in a condition, 21 times, the most; using == instead of ===, with types quietly converted, 18 times; forgetting break in a switch and falling through to the next case, 16 times; writing only half of a comparison on either side of ||, 13 times; else if branches in the wrong order, with the loose condition blocking the strict one, 11 times; treating empty strings and 0 as "has a value", 9 times; nesting so deep that nobody can tell which if an else belongs to, 7 times; nesting the ternary two levels or more until it is unreadable, 5 times. 21 + 18 + 16 + 13 + 11 + 9 + 7 + 5 = 100, and the books balance.

Bar chart: breakdown of 100 fictional conditional mistakes in one month on the Greenstone Cafe order page, assignment instead of comparison 21 times, the most

Before the order page's conditional logic goes live, run through these seven questions. First, are the comparisons right? === or ==, one equals sign or two — whenever = appears in a condition, stop and check whether it is an assignment. Second, are truthy and falsy clear? Empty strings, 0, null, undefined, and NaN are falsy, while the string "0", an empty array, and an empty object are truthy — do not mistake a legitimate 0 for nothing. Third, are both sides of || complete comparisons? A half-written comparison like x === 5 || 7 makes the condition always true. Fourth, do the else if branches run from strict to loose? A loose condition placed first blocks the strict one, so boundary values must be tested one by one. Fifth, does every switch case have an exit? No break and no return means fall-through — ask whether that is deliberate or forgotten. Sixth, is the ternary nested more than one level? It only passes if it reads smoothly in one breath; if it twists your tongue, split it back into if...else. Seventh, is the nesting more than two levels deep? Beyond two levels, think about extracting a function or flattening the code with guard clauses. Once those seven questions are answered, go back to MDN's three docs: the Learn article covers the basic ideas and examples of conditionals, the if...else reference is the complete manual for the if statement, and the switch reference is the rulebook for switch. The three have different jobs, so do not go to the wrong door when checking a problem: for whether a particular form is allowed, read the matching reference; for how conditions should be organized overall, go back to the Learn article. One last reminder: the full rules of type conversion and condition combinations inside loops, which this guide did not cover, each have their own traps — read the matching MDN docs before writing from memory.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles

Real photo: hands typing on a MacBook Pro showing JavaScript code that changes HTML content, with a white mouse, papers, and binders on a white desk
Guide
Functions without the confusion: JavaScript functions, parameters, and arrow functions, explained plainly

You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.

Tool TipsFrontend EngineeringAI Coding
Real photo: a Casio scientific calculator on a wooden desk showing 123456789 + 987654321 = 1111111110, beside handwritten math notebooks, a pen, a mug, and a laptop edge
Guide
Don't let 0.1 + 0.2 break your bill: JavaScript numbers and Math, explained plainly

Numbers in JavaScript are one type, Number, stored as 64-bit floats — which is why 0.1 + 0.2 is 0.30000000000000004. This guide follows MDN's Basic math in JavaScript, Math, and Number: one number type, float error, counting money in cents, converting strings, NaN and Infinity, safe integers, the four rounding methods, Math.random, the Math toolbox, and formatting for display.

Tool TipsFrontend EngineeringAI Coding
Real photo: over-the-shoulder view of a man typing CSS code on a laptop, selectors visible on screen, with coffee, glasses, and a phone on the desk
Guide
Getting styles onto the right elements: CSS selectors, explained plainly

A selector is the first part of a rule: it decides who the styles land on. This guide follows MDN's Basic CSS selectors, Attribute selectors, and Pseudo-classes and pseudo-elements: type, class, ID, selector lists, universal, attribute selectors, pseudo-classes, pseudo-elements, chaining them together, plus a checklist for when a style does not show up.

Tool TipsFrontend EngineeringAI Coding