Choosing by Exact Value
Sometimes you compare one variable against a list of exact values. You could write a long else-if chain, but switch does this job more clearly:
const day = 6;
switch (day) {
case 1:
console.log("Monday");
break;
case 6:
console.log("Saturday");
break;
default:
console.log("Invalid day");
}
Output:
Saturday
switch reads the value of day once. Then it looks for the case with the same value and runs the lines under it. If no case matches, the default part runs. Use switch for exact values, like day numbers or command words. If you need ranges, like "75 or more", use an else-if chain, because a case can only hold one exact value.
switch compares with ===, so the type must match too. The text "6" does not match case 6:
const day = "6";
switch (day) {
case 6:
console.log("Saturday");
break;
default:
console.log("No match");
}
Output:
No match
This matters when you read input, because input always arrives as a string. Convert it with Number() first.
Now the most important rule. A case only marks a place to start. JavaScript starts running at the matching case and keeps going down, through the cases below it, until it reaches a break or the end of the switch. This is called fall-through. Here is what happens when a break is missing:
const day = 0;
switch (day) {
case 0:
console.log("Sunday");
case 1:
console.log("Monday");
break;
}
Output:
Sunday
Monday
day matched only case 0, but both lines printed. Fall-through causes many bugs, so make it a habit: end every case with break.
There is one good use of fall-through. You can stack empty cases so that several values share the same code:
const day = 7;
switch (day) {
case 6:
case 7:
console.log("Weekend");
break;
default:
console.log("Weekday");
}
Output:
Weekend
case 6 has no code of its own, so it falls into the code under case 7. This is how you say "6 or 7" in a switch.
In the exercise, add the cases for the rest of the week, with a break in each one.