Skip to content
BENIBIX Learn

Switch Statement

Development🧩 Programming ConceptsControl Flow

Also known as Switch Case, Match Statement, Case Statement

Checks one value against a list of cases and runs the one that matches.

Think of it like

It is like a sorting machine for coins. Each coin size drops into its own slot.

Example

A game reads the key pressed. The switch runs one case for up, one for down and a default for any other key.

Why it matters

Many choices hang on one value, like a menu pick or a status. A switch lays them out in one clear list.

Definition

A switch statement checks one value against a list of cases and runs the matching one. It does the job of a long chain of if and else lines, but is easier to read. A default case runs when nothing matches. In C and JavaScript, each case needs a break, or the next case runs too. Python 3.10 added a match statement that does the same job.

Example code

javascript
switch (day) {
  case "Sat":
  case "Sun":
    console.log("Weekend");
    break;
  default:
    console.log("School day");
}
Two cases share one answer. Every other day falls to default.
One value meets many doors. Only the matching door opens.

Common mistake

Leaving out break in C or JavaScript. The code then falls through and runs the next case as well.

Key takeaways

  1. 1
    One value. Checked against many cases.
  2. 2
    Default case. Catches anything not listed.
  3. 3
    Mind fall-through. Some languages need break.

Learn it properly