Learn JavaScript
❯ control_flow.switch

The switch Statement in JavaScript

$concept

switch dispatches on a value to labeled case branches using strict (===) comparison — cleaner than long === chains when one variable decides everything. Execution falls through from the matching case into every case below unless break (or return) stops it.

Cases accept any expression, evaluated once against the switch value with ===. default catches unmatched values. switch(true) with boolean case expressions emulates if-chains, though plain ifs usually read better for that shape.

$how it works
1

Strict dispatch

switch (day) jumps to the case strictly equal — 3 matches case 3, never case "3".

2

break stops fallthrough

Without break, execution slides into the next case — end every case with break/return unless sharing deliberately.

3

default handles the rest

default: runs when nothing matched — the else of the switch world.

4

Any case expression

Cases can be variables and expressions (not just literals) — all compared with === against the switch value.

$example
let day = 3;
switch (day) {
case 1: console.log("Mon"); break;
case 3: console.log("Wed"); break;
default: console.log("other"); break;
}
Output
Wed
1day is 3 — jumps directly to case 3, skipping case 1.
2Wed prints, then break exits — without it, other would print too.
3One line proves single-case dispatch.
$use cases
Menu and command dispatch on one variable
State machines with one case per state
Stacked cases sharing handling (vowels, weekends)
Replacing === chains where dispatch reads cleaner

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.