Switch Statements in JavaScript

Introduction

A switch statement compares one value against multiple cases and runs the matching branch. It is often cleaner than long else if chains when you compare the same variable against many constants. This chapter covers switch, break, default, and fall-through rules.

Prerequisites

Basic switch Syntax

javascript
// Route by command name
const command = "start";
 
switch (command) {
  case "start":
    console.log("Starting service");
    break;
  case "stop":
    console.log("Stopping service");
    break;
  case "status":
    console.log("Reporting status");
    break;
  default:
    console.log("Unknown command");
}

break stops the switch after a case runs. Without break, execution falls through to the next case.

Strict Comparison (===)

switch uses strict equality (===), not loose ==:

javascript
// Number 1 does not match string "1"
const code = 1;
 
switch (code) {
  case 1:
    console.log("Numeric one");
    break;
  case "1":
    console.log("String one");
    break;
}

default Case

Handles values that match no case:

javascript
// Grade label with default
const grade = "Z";
 
switch (grade) {
  case "A":
    console.log("Excellent");
    break;
  case "B":
    console.log("Good");
    break;
  default:
    console.log("Unlisted grade");
}

Fall-Through (Intentional)

Sometimes multiple cases share logic:

javascript
// Group cases without break
const month = 2;
let quarter;
 
switch (month) {
  case 1:
  case 2:
  case 3:
    quarter = "Q1";
    break;
  case 4:
  case 5:
  case 6:
    quarter = "Q2";
    break;
  default:
    quarter = "Other";
}
 
console.log(quarter);

Warning

Accidental fall-through is a common bug. Add break unless grouping is intentional—and comment why.

switch vs if / else if

Use switch whenUse if when
Same variable, many discrete valuesRanges (score > 80)
Constants / enumsComplex boolean logic
Readable command routingFew branches (2–3)

Mini Example: HTTP Status Handler

javascript
// Map status codes to messages
const status = 404;
let message;
 
switch (status) {
  case 200:
    message = "OK";
    break;
  case 201:
    message = "Created";
    break;
  case 400:
    message = "Bad Request";
    break;
  case 404:
    message = "Not Found";
    break;
  case 500:
    message = "Server Error";
    break;
  default:
    message = "Unhandled status";
}
 
console.log(`${status}: ${message}`);

FAQ

Can switch use ranges like score >= 90?

Not directly—each case is one value. Use if chains or convert to buckets first.

Does switch work on strings?

Yes—very common for commands, roles, and status codes.

What is a switch (true) pattern?

An advanced style for complex conditions—learn if deeply first.

What comes next?

For loops and while loops.