JavaScript AcademyProfessional Engineering
Level 1 · FoundationsModule 3: Decisions and LogicLesson 14 of 150About 40 minutes

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.

You need: Lesson 13: If, else if and else

Skills practised: Logic, Conditional statements.

04Explanation

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 operator condition ? valueIfTrue : valueIfFalse chooses between two values in one expression: const label = stock > 0 ? "In stock" : "Sold out";.

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.

Open the full glossary

06Visual learning object

Switch statement visualizer. Step through a switch and see which case matches, and what happens when break is missing.

Loading the interactive object…

Open the full Switch statement visualizer page with its guided experiment.

07Examples

ex-014-01switch with break Browser-executable JavaScript

Exactly one case runs because each ends with break.

const day = "sat";
switch (day) {
  case "sat":
    console.log("Open 10–16");
    break;
  case "sun":
    console.log("Closed");
    break;
  default:
    console.log("Open 9–18");
}
Sample input
None
Expected output
Open 10–16
Common mistake
Forgetting break, so the next case's message prints too.
Try this
Add a case for "fri" with late opening hours.
Source
examples/ex-014-01-switch-basic.js (repository pending publication)

ex-014-02Missing break: fall-through Browser-executable JavaScript

Without break, execution continues into the next cases.

const level = 2;
switch (level) {
  case 1:
    console.log("Welcome pack");
  case 2:
    console.log("Discount voucher");
  case 3:
    console.log("Free delivery");
}
Sample input
None
Expected output
Discount voucher Free delivery
Common mistake
Assuming only the matching case runs when there is no break.
Try this
Add break statements so level 2 only gets the voucher.
Source
examples/ex-014-02-fall-through.js (repository pending publication)

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`);
Sample input
None
Expected output
Month 2 has 28 days
Common mistake
Writing case 4, 6, 9: (commas do not list cases).
Try this
Change month to 9 and to 12.
Source
examples/ex-014-03-grouped-cases.js (repository pending publication)

ex-014-04The conditional operator Browser-executable JavaScript

A ternary chooses between two values inside an expression.

const stock = 0;
const label = stock > 0 ? "In stock" : "Sold out";
console.log(label);
const items = 1;
console.log(`${items} ${items === 1 ? "item" : "items"} in your cart`);
Sample input
None
Expected output
Sold out 1 item in your cart
Common mistake
Nesting several ternaries until nobody can read the line.
Try this
Set items to 3 and run.
Source
examples/ex-014-04-ternary.js (repository pending publication)

08Guided exercises

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);

More cases in the Debugging Detective Laboratory

11Practical scenario

Order status dashboard

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

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

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.

16AI learning prompts

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 explanation switch 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 prediction Fall-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.
Debugging Extra 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 generation Menu 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 review Ternary 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.