LESSON 12

Switch Statements

Learning objective: Handle many discrete cases with switch.

Understand

A switch is a clean way to compare one value against many options.

switch checks a value against several case labels and runs the matching block. Use break to stop fall-through and default for unmatched values. It reads better than a long if/else chain for exact matches.

Analogy: A switch is like a vending machine: press a specific button and get that specific item.

See It in Action

Matching a day:

switch (day) {
  case "Sat":
  case "Sun":
    console.log("Weekend");
    break;
  default:
    console.log("Weekday");
}
How it works: 'Sat' and 'Sun' share a block, and default handles everything else; break stops the code falling into other cases.

Try It Yourself

  1. Write a switch on a variable with three cases.
  2. Add a default case.
  3. Remove a break and observe fall-through.

Quick Quiz

What does break do in a switch?

Challenge

Use a switch to print a message for at least three input values.

Success condition: Your switch handles each case and a default correctly.