Switch & the Ternary Operator
Two cleaner ways to write certain decisions — switch for many cases, ternary for quick one-liners.
What you will learn
- Use a switch statement
- Write a ternary expression
- Choose the clearest tool
switch — many fixed cases
When you compare one value against many options, switch is tidier than a long if/else chain.
<script>
let day = 3;
let name;
switch (day) {
case 1: name = "Monday"; break;
case 2: name = "Tuesday"; break;
case 3: name = "Wednesday"; break;
default: name = "Other";
}
document.write(name);
</script>Here is how a switch runs step by step:
switch (day)takes the value to test — heredayis 3.- It compares that value against each
casefrom top to bottom. case 1andcase 2do not match, so they are skipped.case 3matches, soname = "Wednesday"runs.breakstops the switch right there. (defaultonly runs if no case matched.)
Note: Output: Wednesday
Watch out: Do not forget break after each case — without it, JavaScript “falls through” and runs the next cases too.
Ternary — a one-line if/else
The ternary operator condition ? a : b returns a if true, else b — perfect for short choices.
<script>
let age = 20;
let status = age >= 18 ? "Adult" : "Minor";
document.write(status);
</script>Read it as a quick question: "Is age >= 18?" Since age is 20, the answer is yes, so the value before the colon ("Adult") is chosen and stored in status. If age were under 18, the value after the colon ("Minor") would be chosen instead.
Note: Output: Adult
Q. What keyword stops a switch case from falling through to the next?
✍️ Practice
- Use a
switchto turn a number 1–7 into a day name. - Rewrite a simple if/else as a ternary.
🏠 Homework
- Build a tiny calculator that uses
switchon an operator (+, -, *, /).