JavaScript switch

Compare one value against many options cleanly with switch.

Lesson 13 of 56Beginner13 min read

When you compare one value against many possible matches, such as a day of the week, a menu choice or a key press, a long chain of else if statements becomes repetitive. The switch statement lays those options out like a menu, one case per line.

switch is one of several ways to handle "choose one of many" decisions. This lesson shows how it works, the one trap to watch for, and when a simpler alternative is the better choice.

How the switch statement works

JavaScript
switch (fruit) {
  case "apple":
    console.log("Crunchy!");
    break;
  case "banana":
    console.log("Potassium!");
    break;
  default:
    console.log("A mystery fruit.");
}
  1. The value in brackets is compared with each case using strict equality (===).
  2. When a case matches, its code runs.
  3. break ends the switch. Without it, the code falls through into the next case and runs that too.
  4. default runs if nothing matched, much like a final else.

Because the comparison is strict, case 1 won't match the string "1". Values read from forms or the page are strings, so convert them first if your cases are numbers.

Grouping several cases together

Stack cases with no code between them to share one block:

JavaScript
case "Saturday":
case "Sunday":
  console.log("Weekend!");
  break;

This is the one situation where falling through is useful and deliberate. Anywhere else, a missing break is almost always a bug.

How switch compares values

switch uses strict equality (===) to compare the value with each case. That means switch (input) with case 1: won't match when input is the string "1", which is a common surprise when values come from form fields or URLs. Convert first with Number(input), or write the cases as strings.

Each case only marks a starting point. Once a case matches, JavaScript runs every line below it, through later cases too, until it reaches a break or return. Leaving out break by mistake is the classic switch bug, but doing it on purpose is how several cases share the same code. Inside a function, return ends the switch and the function at once, so you don't need break after it.

Using switch inside a function

In a function, return can replace break, because returning ends the function straight away:

JavaScript
function dayType(day) {
  switch (day) {
    case "Saturday":
    case "Sunday":
      return "weekend";
    default:
      return "weekday";
  }
}

This pattern is compact and avoids forgotten break statements entirely.

JavaScript switch Syntax

switch syntax

switch (expression) {
  case value1:
    // code
    break;
  case value2:
  case value3:
    // shared code
    break;
  default:
    // no match
}

JavaScript switch Summary

  • switch compares one value against many case values using ===.
  • break stops the switch; without it, code falls through to the next case.
  • default runs when no case matches.
  • Stack cases to share one block of code.
  • Use if for ranges and an object lookup for simple value mapping.

JavaScript switch Examples

Each example runs in the page. Edit the code and press Run to see what changes.

Example 1

Traffic light

Change light to "red", "amber", "green" and "blue".

const light = "amber";

switch (light) {
  case "red":
    console.log("🛑 Stop");
    break;
  case "amber":
    console.log("🟠 Get ready");
    break;
  case "green":
    console.log("🟢 Go");
    break;
  default:
    console.log("⚠️ Unknown signal");
}
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 3The value to check.
  2. Lines 7 to 9"amber" matches this case; break jumps out of the switch.
  3. Lines 13 to 14default handles anything unexpected.
Example 2

Grouped cases

const day = "Sun";

switch (day) {
  case "Sat":
  case "Sun":
    console.log("Weekend: time for a lie-in! 😴");
    break;
  case "Fri":
    console.log("Almost there 🎉");
    break;
  default:
    console.log("Work day 💼");
}
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 4 to 7"Sat" and "Sun" share the same block.
Example 3

Fall-through in action

break is missing in the first two cases. Run it and watch every case below the match run too.

const level = 1;

switch (level) {
  case 1:
    console.log("Unlocked: sword");
  case 2:
    console.log("Unlocked: shield");
  case 3:
    console.log("Unlocked: dragon");
    break;
}
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 4 to 5Matches, then falls through…
  2. Lines 6 to 9…running cases 2 and 3 as well, until a break. Occasionally useful, usually a bug.

Common JavaScript switch Mistakes

Forgetting break

Don't
switch (size) {
  case "S": price = 5;
  case "M": price = 7;
  case "L": price = 9;
}
// price is always 9!
Do
switch (size) {
  case "S": price = 5; break;
  case "M": price = 7; break;
  case "L": price = 9; break;
}

Using switch for ranges

Don't
switch (score) {
  case score > 90: grade = "A"; break; // compares score === true
}
Do
if (score > 90) { grade = "A"; }

Cases are compared with ===, so conditions like score > 90 don't work as you'd expect.

JavaScript switch in Real Projects

Where switch shines

Keyboard controls in games (case "ArrowLeft"), handling actions in state management libraries like Redux (case "ADD_TODO"), routing simple commands in chatbots, and mapping status codes to messages are classic switch use cases.

JavaScript switch Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the switch.

switch (pet) {
   "dog":
    console.log("Woof");
    ;
  :
    console.log("...");
}
Predict the outputmedium

What does this print?

const x = "2";
switch (x) {
  case 2:
    console.log("number");
    break;
  default:
    console.log("no match");
}
Multiple choicemedium

What happens if a matching case has no break?

Fix the bugmedium

Picking "M" should log Price: 7, but it logs Price: 9. Fix it.

const size = "M";
let price;

switch (size) {
  case "S":
    price = 5;
  case "M":
    price = 7;
  case "L":
    price = 9;
}

console.log("Price:", price);
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Logs "Price: 7"

JavaScript switch Quiz

3 questions to check what you learned.

  1. What does default do in a switch?

    • Runs when no case matches
    • Runs first
    • Sets a default value
    • Is required
  2. Which comparison does switch use?

    • ==
    • >
    • It depends on the type
    • ===
  3. How do you make two cases run the same code?

    • case "a" || "b":
    • case ["a", "b"]:
    • Write case "a": and case "b": one after the other, then the code
    • It's not possible

JavaScript switch Challenge

Keyboard controls

Write a switch on key that logs:

  • "ArrowUp" or "w" → Jump
  • "ArrowDown" or "s" → Duck
  • " " (space) → Shoot
  • anything else → Ignored

Then call it for the given key so it logs Duck.

const key = "s";
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Logs "Duck"
  • Logs nothing else
  • Uses a switch statement