switch
- Node.js course
- Beginner
- Lesson 38/116
- 5 min
Learn multi-way selection with switch, case, break and default.
switch basics
To select among many cases based on a variable's value you use switch. The form is switch (value) { case x: ...; break; default: ...; }. A case label marks a value, break exits, and default runs when no case matches.
For example a day name: switch (day) { case 1: console.log("Monday"); break; case 2: console.log("Tuesday"); break; default: console.log("Unknown"); }. switch looks at many possible equalities of one value; if/else if is better for range checks.
break and fall-through
If you omit break in a switch, the cases after the matching one also run in order. This behavior is called fall-through. It is usually unwanted, so each case ends with break.
Sometimes fall-through is useful: when several values should run the same code, the cases are stacked. For example case 1: case 2: console.log("Weekday"); break; makes 1 and 2 produce the same output. Except for intentional fall-through, always using break is safe.
Practice Print the day name
The day variable is set to 2. Write a switch: case 1 prints "Monday", case 2 prints "Tuesday"; each case ends with break. The default prints "Unknown". The output on a single line must be Tuesday.
Starter code
const day = 2;
// Write the switch statement hereSample solution
const day = 2;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Unknown");
}Expected output
Tuesday
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each keyword to its job
| Term | Meaning |
|---|---|
switch |
Starts multi-way |
case |
Labels a value |
break |
Exits the switch |
default |
When no case matched |
2 Write the case label
switch (day) {
____ 1:
console.log("Monday");
break;
}
switch (day) {
case 1:
console.log("Monday");
break;
}
Explanation: case labels a value; when, if and match are not valid switch keywords.
3 What happens if you omit break in a switch?
switch (x) { case 1: console.log("a"); /* no break */ case 2: console.log("b"); break; }- Prints only "a"
- Prints only "b"
- Throws an error
- Fall-through, prints both Correct answer
Explanation: Without break, fall-through happens; both "a" and "b" are printed.