Course contentsShow
← JavaScript
Lesson 320 of 2,7239. Control FlowFree lesson

The Switch Statement Syntax

Learn the basic structure of switch statements with case labels, break keywords, and default clauses.

The Switch Statement Syntax

What you'll learn: You'll discover how to write switch statements with case labels, break keywords, and default clauses to handle multiple branching paths cleanly.

What is a Switch Statement?

A switch statement evaluates an expression once, then compares its value against multiple case labels. When a match is found, the code for that case executes. Think of it like a vending machine: you press one button (the switch expression), and the machine checks which slot matches your selection, then delivers that specific item.

Basic Structure

switch (expression) {
  case value1:
    // Code runs if expression === value1
    break;
  case value2:
    // Code runs if expression === value2
    break;
  default:
    // Code runs if no case matches
}

Key Components

Case Labels

Each case keyword defines a potential match. JavaScript uses strict equality (===) to compare the switch expression against each case value.

Break Keyword

The break statement exits the switch block. Without it, execution "falls through" to the next case, which is usually unintended.

Default Clause

The optional default acts like a final else—it runs when no case matches. It can appear anywhere but conventionally goes last.

Simple Example

let day = 3;

switch (day) {
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  case 3:
    console.log("Wednesday"); // This runs
    break;
  default:
    console.log("Unknown day");
}

Since day is 3, the output is "Wednesday".

Key Takeaway: Switch statements provide a structured way to compare one value against multiple possibilities using case labels, break to prevent fall-through, and default for unmatched cases.