Careeroza
switch
The switch Statement
Example
switch compares one value with many cases using ===. Remember break, or execution falls through to the next case:
function dayType(day) {
switch (day) {
case "Sat":
case "Sun":
return "Weekend";
case "Fri":
return "Almost weekend";
default:
return "Weekday";
}
}
console.log(dayType("Sun"), dayType("Fri"), dayType("Mon"));Output
Weekend Almost weekend Weekday
Object Lookup Alternative
Example
For simple value mapping, an object is often cleaner than a switch:
const statusText = { 200: "OK", 404: "Not Found", 500: "Server Error" };
const code = 404;
console.log(statusText[code] ?? "Unknown");Output
Not Found