For a day name, select one of three outcomes: weekend, weekday, or unknown.
The switch statement is an alternative to long if/else if chains when you are matching a single value against several discrete options.
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code when no case matched
}
When a case logs or assigns a result, use break to stop execution from falling into the next case. In a function, return also stops execution, so a case that returns does not need break.
const light = "amber";
switch (light) {
case "amber":
case "red":
console.log("Stop");
break;
default:
console.log("Go");
}
Adjacent cases can share a result. The switch matches exact values: "Saturday" is not the same as "saturday".
getDayType(day) using switch: Saturday and Sunday return "Weekend", weekdays return "Weekday", and any other name returns "Unknown". The provided Sunday probe should print Sunday: Weekend.Weekend pair: Weekend,Weekend from Saturday and Sunday calls.Weekdays: Weekday,Weekday,Weekday,Weekday,Weekday from Monday through Friday calls.Holiday: Unknown from an invalid name.Saturday: Weekend from getDayType("Saturday").Each case matches the value after switch (expression).
Don't forget break at the end of each case to prevent fall-through.
Use default as the catch-all (like else).