Lesson 14: Switch statements and conditional expressions
01Opening question
An order can be "pending", "paid", "shipped" or "delivered". Is a long else if chain the clearest way to handle each status?
Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.
02Start with working code
switch compares status with each case using ===. break stops it from running into the next case.
const status = "shipped";
switch (status) {
case "paid":
console.log("Preparing your order");
break;
case "shipped":
console.log("On its way");
break;
default:
console.log("Unknown status");
}
03Objective and prerequisites
Learning objective: Use switch for one value compared against many cases, remember break, and use the conditional (ternary) operator for short two-way choices.
switch compares one value against a list of case values and runs the matching case. It reads well when you have many exact values, such as statuses or menu choices.
Each case usually ends with break. Without it, JavaScript keeps going into the next case (fall-through), which is occasionally useful but usually a bug.
default runs when no case matches, like the final else.
The conditional operatorcondition ? valueIfTrue : valueIfFalse chooses between two values in one expression: const label = stock > 0 ? "In stock" : "Sold out";.
switch uses strict equality (===) to compare the discriminant with each case expression. Cases are evaluated in order and the first match wins.
Intentional fall-through should be marked with a comment (// falls through), which linters recognise. Grouping several case labels on one block is the common legitimate use.
Case blocks share one scope; wrap a case's statements in braces when declaring let/const inside it to avoid redeclaration errors.
Many teams prefer an object lookup (const labels = { paid: "…" }) over switch for pure value mapping. Nested ternaries harm readability; keep the conditional operator for simple two-way choices.
05Definitions
switch
Compares one value with several cases and runs the matching one.
case
A value in a switch to compare against.
break
Stops a switch (or loop) immediately.
default
The switch branch that runs when no case matches.
Fall-through
Running into the next case because break was left out.
Conditional (ternary) operator
condition ? a : b: chooses a value in one expression.
ex-014-03Grouping cases on purpose Browser-executable JavaScript
Several case labels can share one block.
const month = 2;
let days;
switch (month) {
case 4: case 6: case 9: case 11:
days = 30;
break;
case 2:
days = 28;
break;
default:
days = 31;
}
console.log(`Month ${month} has ${days} days`);
Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.
Add the missing breaks
Stop unwanted fall-through.
const size = "M";
switch (size) {
case "S":
console.log("Small: 10");
case "M":
console.log("Medium: 12");
case "L":
console.log("Large: 14");
}
Order status messages
Write a switch with a default.
const status = "delivered";
let message;
// TODO: switch on status:
// "pending" → "Waiting for payment"
// "shipped" → "On its way"
// "delivered" → "Delivered. Enjoy!"
// anything else → "Status unknown"
console.log(message);
Cart badge text
Use ternaries for small two-way choices.
const count = 1;
const total = 0;
09Prediction
Commit to an answer first, then run the real code to compare.
const x = 3;
switch (x) {
case 1: console.log("one");
case 3: console.log("three");
case 4: console.log("four"); break;
default: console.log("other");
}
What is printed?
10Debugging investigation
Silver members get two discounts
Silver members should get 10% off. The checkout applies 10% and then another 5%, and the final price is too low.
const tier = "silver";
let price = 100;
switch (tier) {
case "gold":
price = price * 0.8;
case "silver":
price = price * 0.9;
case "bronze":
price = price * 0.95;
}
console.log("Price:", price);
Status values come from a fixed list, so a switch (or a lookup object) maps each status to its message and colour. The default branch catches any new status the back end introduces.
const s = "refunded";
switch (s) { case "paid": console.log("green"); break; default: console.log("grey"); }
12Knowledge check
1. What does this print?
console.log(5 > 10 ? "Yes" : "No");
Yes
No
true
An error
2. What does break do inside a switch?
Skips the next case only
Stops the switch
Restarts the switch
Causes an error
3. Which comparison does switch use?
==
===
>
It depends
4. What does this print?
switch ("1") { case 1: console.log("one"); break; default: console.log("none"); }
none
one
An error
nothing
5. Why do both messages print?
switch ("a") { case "a": console.log("A"); case "b": console.log("B"); }
Two cases matched
The first case has no break
default always runs
switch needs else
6. For mapping 12 menu keys to actions, which is usually clearest?
12 nested ternaries
A switch or a lookup object
12 separate if statements without else
A loop
13Solutions and tests
Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.
Automated acceptance tests for this lesson
These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.
Add the missing breaks: Prints only Medium: 12; Has breaks and a default
Order status messages: Prints the delivered message; Uses switch with default
Cart badge text: Prints 1 item | Free; Uses two ternaries; badge is correct
ex-014-01: output matches the documented expected output
ex-014-02: output matches the documented expected output
ex-014-03: output matches the documented expected output
ex-014-04: output matches the documented expected output
The lesson lives in the companion repository at curriculum/level-01-foundations/module-03-decisions-and-logic/lesson-014-switch-statements-and-conditional-expressions/. Every example on this page is generated from those files.
The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.
15Summary and next steps
switch compares one value with several cases using ===.
End each case with break unless fall-through is intended and commented.
default handles unmatched values.
Use condition ? a : b for short two-way choices; avoid nesting it.
Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.
Concept explanationswitch versus if
Context: I know if/else if and am learning switch.
Task: Explain when switch reads better, with two side-by-side examples.
Constraints: Beginner level.
Expected behaviour: I can choose between switch and if.
Testing: Give me two scenarios to decide.
Code predictionFall-through puzzles
Context: I know break and default.
Task: Give me five switch statements with missing breaks and ask what prints.
Constraints: Wait for answers.
Expected behaviour: Each has one exact output.
Testing: Explain the flow for any I miss.
DebuggingExtra messages
Context: My switch prints two messages instead of one.
Task: Help me find why.
Constraints: Questions first.
Expected behaviour: I fix it myself.
Testing: Ask me to add a log at each case.
Exercise generationMenu choices
Context: I finished the order status exercise.
Task: Create two switch exercises (calculator operator, keyboard shortcut).
Constraints: Exact expected output.
Expected behaviour: Each has a default.
Testing: Include expected output for three inputs.
Code reviewTernary readability
Context: My code has a ternary nested three levels deep.
Task: Rewrite suggestions that are easier to read.
Constraints: Same behaviour.
Expected behaviour: No nested ternaries.
Testing: List inputs and outputs that prove equivalence.