Learn by reading through in order

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
}
How an else if Chain Is Evaluated
Startscore = 4.8ifscore >= 4.5Excellentelse ifscore >= 3.5GoodelseBelow averagetruefalsetruefalseotherwise

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 scoreChecked from the topPrinted line
4.84.5 or higher is true, so checking stops hereExcellent (1 line only)
3.84.5 or higher is false / 3.5 or higher is trueGood (1 line only)
2.1Both are false, so else runsBelow 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.

Turn an order's state into a status message. orderId, isCanceled, isShipped, and isPaid are already declared.

① Print a line in the form "Status of order A-1001".

② Write a branch that prints "Canceled" if the order has been canceled.

③ Then add branches, in this order, that print "Shipped" if it has shipped and "Preparing to ship" if it has been paid.

④ If none of these apply, print "Awaiting payment".

(If it runs correctly, an explanation will appear.)

JavaScript / TypeScript Editor

Run code to see output

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
How the Ternary Operator Becomes One Value
stock > 0 ?"In stock" :"Out of stock"Condition, truevalue, false valuestock is 00 > 0 is falseThe condition isevaluated firstPicks "Out ofstock" right of :If true, picks thevalue right of ?const badge ="Out of stock"The chosen valueis the result
The condition 0 > 0 is false, so "Out of stock" to the right of : is chosen. The whole expression becomes a single value and goes straight into the const.

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.

Print a heading for the reviews and the points a purchase earns. reviewCount, isPremium, and purchaseAmount are already declared.

① Print a heading that says "No reviews yet" when there are 0 reviews, and "Reviews: ◯" when there's at least 1.

② Store a point rate in a variable: 0.03 for premium members and 0.01 for everyone else.

③ Multiply the purchase amount by the rate from ②, round down, and print "Points earned: ◯ pt (Regular member)", with the membership label switching as well.

JavaScript / TypeScript Editor

Run code to see output

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");
}
The Matching case and the default Branch
Pass increditMatchescase creditRuns that branch,exits with breakNo feePass inbankMatches none ofthe 3 casesRuns thedefault branchPlease choose apayment method
credit exits at the first case, while bank matches none of the three. Only a value that matches nothing reaches the default branch.

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.

Work out the shipping fee from the shipping method. shippingMethod, itemTotal, and shippingFee are already declared.

① Use switch to set the shipping fee to 500 for standard and 900 for express.

② Add a branch that sets it to 0 for store (in-store pickup).

③ If none of these apply, print "Please check the shipping method".

④ After the switch, print "Shipping: ◯ yen / Total: ◯ yen".

JavaScript / TypeScript Editor

Run code to see output

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;
}
With break vs. Without break
Status: paidMatchescase paidbreak exitsthe switch1 line printedStatus: paidMatchescase paidCases belowrun too3 lines printed
With the same paid status, leaving out break also prints "Shipped" and "Please check the status." Whether break is there changes how many lines are printed.

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.

Print the features available on each pricing plan. The variable plan, which holds the current plan, is already declared.

① Print a heading in the form "Features on the standard plan".

② Write a switch and print "Offline playback" in the premium branch.

③ Below it, add a standard branch that prints "HD quality" and a free branch that prints "Video streaming", without writing break.

④ Add a case so that trial runs the same code as free.

JavaScript / TypeScript Editor

Run code to see output
QUIZ

Knowledge Check

Answer each question one by one.

Q1In an else if chain with >= 50000 first and >= 100000 after it, which branch runs when you pass in 120000?

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?