The switch statement compares one value against a list of possible matches and runs the code for the one that fits. When you find yourself writing else if (day === ...) over and over with the same variable, a switch is usually cleaner and easier to read.
switch (expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
switch expression is evaluated oncecase, top to bottomdefault code runs (if there is one)Notice the punctuation: each case value is followed by a colon, not braces, and the whole thing is wrapped in one pair of braces.
This turns a weekday number into its name. JavaScript numbers the days 0 to 6, starting with Sunday:
let dayNum = 2;
let day;
switch (dayNum) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
console.log(day);
2 with new Date().getDay(), which gives today's weekday as a number from 0 to 6, and the switch prints today's name. Dates get their own lessons in the JS Dates section.
When JavaScript reaches break, it jumps out of the switch. No more code inside it runs.
Without break, something surprising happens: after a match, JavaScript keeps going and runs the code of the following cases too, even though their values do not match. This is called fall-through:
let level = 2;
switch (level) {
case 1:
console.log("one");
case 2:
console.log("two"); // match starts here...
case 3:
console.log("three"); // ...and falls through
default:
console.log("default"); // ...all the way down
}
break does not cause an error. The code runs, just with extra cases firing. End every case with break. The one exception: the last case does not need one, because the switch ends there anyway. (Many programmers add it anyway, so it is not forgotten when another case is added below.)
default is the code to run when no case matches. It works like the final else in an if...else if chain:
let dayNum = 3;
let text;
switch (dayNum) {
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the weekend";
}
console.log(text);
A few rules about default:
default and no match, nothing in the switch runs, and the program carries on after itbreak, or it falls through into the case below itFall-through is occasionally what you want. Stack several case labels with no code between them, and they all share the next block:
let dayNum = 5;
let text;
switch (dayNum) {
case 4:
case 5:
text = "Soon it is the weekend";
break;
case 0:
case 6:
text = "It is the weekend";
break;
default:
text = "Looking forward to the weekend";
}
console.log(text);
Here 4 and 5 (Thursday and Friday) share one block, and 0 and 6 (the weekend) share another. This is the one form of fall-through that is clearly intentional, because there is no code between the grouped labels.
switch compares using strict equality (===). The value and the case must be the same type to match:
let x = "0"; // a string
let text;
switch (x) {
case 0: // a number: no match
text = "Off";
break;
case 1:
text = "On";
break;
default:
text = "No value found";
}
console.log(text);
"1" and your cases are written case 1:, nothing ever matches. Convert first, switch (Number(choice)), or write the cases as strings.
Two more details: if more than one case has the same value, only the first is used. And the case values do not have to be plain numbers or strings; they can be any expression, though simple values are by far the most common.
| Use switch when | Use if...else if when |
|---|---|
| One variable is checked every time | Different conditions check different variables |
| You match exact values ("red", 3) | You test ranges (score >= 90) |
| There are many options (roughly 4 or more) | There are only two or three options |
What does this log?
let fruit = "apple";
switch (fruit) {
case "apple":
console.log("red");
case "banana":
console.log("yellow");
break;
default:
console.log("unknown");
}
red then yellow. The apple case has no break, so it falls through into the banana case, which then breaks before reaching default.When does the default block run?
undefineddefault is the no-match fallback, wherever it is placed. The only other way to reach it is falling through from a case with no break.Which is the best fit for a switch?
if...else or a ternary.season with four cases ("spring", "summer", "fall", "winter") and a defaultbreak and run it to watch the fall-through. Put it back"1" with case 1:. Confirm it does not match, then fix it with Number()