Q1In an else if chain with >= 50000 first and >= 100000 after it, which branch runs when you pass in 120000?
Conditionals — else if, the Ternary Operator, and switch
Learn JavaScript conditionals from the ground up: else if for step-by-step checks, the ternary operator that returns a value, and switch with break.
When you're working out a membership tier or showing an order's status, conditions rarely split cleanly into two. If you write Platinum, Gold, and Regular as three separate if statements, the lower conditions are still checked even after an upper one has settled the result, and you get a line of output for every condition that matches.
This article covers else if for checking conditions in stages, the ternary operator that returns a value directly, and switch for matching one value against several candidates.
Splitting into Three or More Cases — Chaining else if
Let's assign a rating label based on a product's average review score. A score of 4.5 or higher is "Excellent," 3.5 or higher is "Good," and anything below that is "Below average."
Two separate if statements are checked independently, so with a score of 4.8 both conditions are true and two lines are printed: "Excellent" and "Good."
Chaining else if (a follow-up condition that's checked only when the previous condition was false) turns several conditions into a single branching structure. The block in { } after each condition is called a branch.
The conditions are checked from top to bottom, and only the first branch whose condition is true runs. If none of them match, the else branch runs.
const score = 4.8; // average review score for a product
// Separate if statements are each checked independently
if (score >= 4.5) {
console.log("Excellent"); // true
}
if (score >= 3.5) {
console.log("Good"); // also true → 2 lines printed
}
// Chained with else if, the first matching branch ends the check
if (score >= 4.5) {
console.log("Excellent"); // only this one runs
} else if (score >= 3.5) {
console.log("Good"); // never checked
} else {
console.log("Below average"); // never checked
}
A score of 4.8 satisfies score >= 4.5 at the first step and exits to the right, so the second step is never checked. The arrow moves down to the next step only when the condition is false.
You can leave out else. Without it, if none of the conditions match, no branch runs and execution moves on to the line after the whole structure.
The table below shows where the checking stops when three different scores go through the same chain.
| Average score | Checked from the top | Printed line |
|---|---|---|
| 4.8 | 4.5 or higher is true, so checking stops here | Excellent (1 line only) |
| 3.8 | 4.5 or higher is false / 3.5 or higher is true | Good (1 line only) |
| 2.1 | Both are false, so else runs | Below average (1 line only) |
The Order of Your Conditions Changes the Result
If you put a condition that covers a wider range first, the narrower conditions below it can never be reached. If you write score >= 3.5 first, a product rated 4.8 ends up as "Good." To rate 4.8 as "Excellent," put the narrower condition, such as score >= 4.5, first.
Getting the Result as a Value — Writing the Ternary Operator
Sometimes you want to switch between "In stock" and "Out of stock" based on the stock count, and store that string in a variable so you can reuse it. With if and else, you can't use const, because a const must get its value the moment it's declared. Instead, you declare the variable with let first and assign to it in each branch.
Code like stock > 0 that produces a value when it's evaluated is called an expression. Code like if (…) { … } that performs actions without producing a value is called a statement.
With the ternary operator (an expression that takes three parts — a condition, a value for true, and a value for false — and evaluates to whichever value is chosen), you can write both branches on one line.
const stock = 0; // stock count
// if is a statement, so declaring and assigning are separate steps
let label;
if (stock > 0) {
label = "In stock";
} else {
label = "Out of stock";
}
console.log(label); // Out of stock
// The ternary operator is an expression, so it can go straight into a const
const badge = stock > 0 ? "In stock" : "Out of stock";
console.log(badge); // Out of stock
// It also works directly inside a template literal
console.log(`Status: ${stock > 0 ? "Available to buy" : "Awaiting restock"}`); // Status: Awaiting restock
When you need three or more outcomes, go back to else if. You can nest ternary operators, but then ? and : show up again and again on one line, as in a ? x : b ? y : z, and you have to trace by eye which condition goes with which value.
Routing by One Value — switch and case
Let's pick a fee message based on the payment method the customer chose. You could write this with else if, but you'd be repeating the same variable over and over — paymentMethod === "credit", paymentMethod === "convenience" — which makes it harder to see what the branching is actually comparing.
With switch (a statement that checks one value against several candidates in order and starts running from the branch that matches), you write the value to compare just once in the parentheses and list the candidates as case value:. The break at the end of a branch exits the switch, and when no case matches, the default: branch runs.
const paymentMethod = "credit"; // payment method the customer chose
switch (paymentMethod) {
case "credit":
console.log("No fee"); // this one runs
break;
case "convenience":
console.log("Fee: 200 yen"); // convenience-store payment; doesn't match
break;
case "cod":
console.log("Fee: 330 yen"); // cash on delivery; doesn't match
break;
default:
console.log("Please choose a payment method");
}
You can leave out default. If a value that matches nothing reaches a switch without one, no branch runs and execution moves on to the next line. When values outside your candidates might show up, printing a message in default makes it show up on screen when something unexpected comes in.
case Matching Treats Strings and Numbers as Different
switch matches values the same way === does, so different types never match. The string "200" read from an input field won't match case 200: and goes to default instead. If a value can be either a number or a string, convert it to one type before matching.
Falling Through to the Next case — Leaving Out break
A common stumbling point with switch is forgetting to write break. The code is still valid, so there's no syntax error; you only notice when you run it and see extra lines of output.
Without a break, execution carries on into the code of the cases below the matching one. This is called fall-through. Execution keeps going — without comparing against the values in the lower case labels — until it hits a break or reaches the end of the switch.
const orderStatus = "paid"; // order status
// Without break, the code below the matching case runs too
switch (orderStatus) {
case "paid":
console.log("Paid"); // matches, starts here
case "shipped":
console.log("Shipped"); // no break, so it continues
default:
console.log("Please check the status"); // runs all the way to default
}
// Stacking cases lets several candidates share one block of code
switch (orderStatus) {
case "pending":
case "paid":
console.log("Not shipped yet"); // both pending and paid end up here
break;
}
You can put this behavior to use when you want several candidates to share the same code. If you stack two case labels with no code between them, a match on the upper case carries straight on into the code below. Put a break at the end of the shared branch.
Knowledge Check
Answer each question one by one.
Q2What does total >= 5000 ? 0 : 500 return when total is 5000?
Q3What happens if you forget to write break at the end of a case?