switch and the Conditional Operator
A switch statement matches one value against a list of exact choices, and the conditional operator ? : picks one of two values in a single line, so a long chain of else ifs can say what it means.
Apprentice · JavaScript · Updated
After this lesson you can
- Choose among exact values with switch, case, break and default
- Pick one of two values with the conditional operator ? :
Key takeaways
- A
switchcompares one value with eachcaseusing===, and runs the code of the case that matches. - End each case with
break, or JavaScript carries on into the next case.defaultruns when no case matches. - The conditional operator
condition ? a : bis read "if this, then that, otherwise that". It gives back one of two values. - Use
ifto choose what to do,? :to choose a value, andswitchto match one value against many exact choices.
Some decisions are a menu: pick one, and you get what goes with it. A music app picks an icon for song, podcast or audiobook. A game turns the key you pressed (up, down, left or right) into a move. A long chain of else if, each asking about the same variable, works, but it buries the menu in repeated code. JavaScript has two tools that say it more clearly: switch for many exact choices, and the conditional operator for picking one of two values.
One value, many choices
Hilltop Bikes rents four kinds of bike, each with its own hourly rate. A vending machine is a good picture of what comes next: you press one button, and you get the snack in that slot.
A switch statement takes one value in parentheses, and compares it with each case in turn. When a case matches, the code after its colon runs:
const bikeType = "mountain";
let hourlyRate;
switch (bikeType) {
case "cruiser":
hourlyRate = 10;
break;
case "mountain":
hourlyRate = 16;
break;
case "electric":
hourlyRate = 22;
break;
default:
hourlyRate = 12;
}
console.log(`A ${bikeType} bike is ${hourlyRate} an hour.`);
A mountain bike is $16 an hour.
case "cruiser":is one choice, read "in the case that it's cruiser". The comparison is===, so the value must match exactly:"Mountain"with a capital M matches no case, and neither does the number3againstcase "3":.breakends theswitch. JavaScript jumps to the first line after its closing}.default:runs when no case matches, here for Hilltop's standard city bike. It's like the finalelseof a chain.
Forgetting break
Without break, JavaScript doesn't stop at the end of a matching case. It carries on and runs the code of the next case too, and the next, until it meets a break or the end. This is called fall-through, and it's a classic bug:
const bikeType = "cruiser";
let hourlyRate;
switch (bikeType) {
case "cruiser":
hourlyRate = 10;
case "mountain":
hourlyRate = 16;
break;
default:
hourlyRate = 12;
}
console.log(`A ${bikeType} bike is ${hourlyRate} an hour.`);
A cruiser bike is $16 an hour.
The cruiser case set the rate to 10, then fell through into the mountain case, which set it to 16. No error, a wrong price.
Fall-through has one good use: several cases that share the same code. Stack them with nothing between them:
const day = "Sunday";
switch (day) {
case "Saturday":
case "Sunday":
console.log("Weekend: $15 an hour.");
break;
default:
console.log("Weekday: $12 an hour.");
}
Weekend: $15 an hour.
Try it. Make bike-rates.js with the first example. Run it with node bike-rates.js for each kind of bike, then for "tandem" (a bike for two), which gets the default. Then delete one break and see which prices go wrong.
Picking one of two values
At the end of a rental, the receipt says 1 bike or 3 bikes. With if and else, that's five lines for one little word. The conditional operator does it in one. It has three parts:
const bikes = 3;
const word = bikes === 1 ? "bike" : "bikes";
console.log(`You rented ${bikes} ${word}.`);
You rented 3 bikes.
Read bikes === 1 ? "bike" : "bikes" aloud as "if bikes is 1, then bike, otherwise bikes". The ? (question mark) comes after the condition, and the : (colon) goes between the two choices. When the condition is true, you get the value before the colon; when it's false, the value after it.
Because it has three parts, it's also called the ternary operator (ternary means "made of three"). That's the name you'll see in most textbooks and on the web.
A value, not an action
The conditional operator gives back a value, so it fits anywhere a value goes: in a variable, inside ${ } in a template literal, or in a sum:
const hours = 2;
const isMember = true;
const hourlyRate = isMember ? 10 : 12;
console.log(`Total: ${hours * hourlyRate} (${isMember ? "member price" : "standard price"})`);
Total: $20 (member price)
It isn't meant for doing things, such as printing one message or another. For that, if and else are easier to read. Here's how to choose:
| You want to | Use |
|---|---|
| run different code depending on a condition | if, else if, else |
| match one value against several exact choices | switch |
| pick one of two values | ? : |
Check yourself
2 questions to try on the lesson page.
So what
switch turns a menu of exact choices into code that reads like the menu, and ? : picks between two values in one line. Both make your decisions clearer, and clear code is easier to get right.