The switch statement
Learn multi-way selection with switch, case, break and default.
switch: branching on a single value
The switch statement makes it easy to choose among many branches based on a variable's value. Each branch starts with a case label and a colon : to mark the value.
let season = 2;
switch (season) {
case 1:
console.log("Winter");
break;
case 2:
console.log("Spring");
break;
default:
console.log("Unknown");
}JavaScript compares the value to each case and runs the first branch that matches. If no case matches, default runs.
default and fall through
The default branch runs when no case matches; it is optional but added for safety. If you forget break, JavaScript falls into the next case too; this is called fall through.
switch (day) {
case 1:
case 2:
console.log("Weekday");
break;
default:
console.log("Other");
}Here case 1 and case 2 share the same output; this uses fall through on purpose. When accidental, it causes serious bugs.
Exercise Write a season switch
The season variable is a number from 1 to 4. Use switch to log the season name: 1 'Winter', 2 'Spring', 3 'Summer', 4 'Autumn'. For unknown values log 'Unknown'. Each case must end with break and there must be a default branch.
Show example solution
let season = 2;
switch (season) {
case 1:
console.log("Winter");
break;
case 2:
console.log("Spring");
break;
case 3:
console.log("Summer");
break;
case 4:
console.log("Autumn");
break;
default:
console.log("Unknown");
}
Test yourself
-
What does the break statement do inside a switch?
- Stops branching and exits the switch
- Starts a new case
- Restarts the switch
- Jumps to the default case
Show answer
Stops branching and exits the switch — Correct. break exits the switch statement and prevents later cases from running.
-
Write the case label
let day = 1; switch (day) { ____ 1: console.log("Monday"); break; }Show answer
let day = 1; switch (day) { case 1: console.log("Monday"); break; } -
Match the switch parts
- switch
- Starts the statement
- case
- Tests a single value
- break
- Stops branching
- default
- Runs when nothing matches