Switch
A switch statement evaluates an expression and compares it against multiple possible case values. They function similarly to if-else blocks but are often much more readable when there are many potential options.
Syntax and Structure
const os = "mac";
let creator;
switch (os) {
case "linux":
creator = "Linus Torvalds";
break;
case "windows":
creator = "Bill Gates";
break;
case "mac":
creator = "Steve";
break;
default:
creator = "Unknown";
break;
}
console.log(creator); // Steve
The Importance of break
Notice the break statement at the end of each case block. Unlike some languages, JavaScript features “fall-through” behavior. If you do not include a break or return statement, the engine will continue executing the code in the next case block, regardless of whether it matched or not.
In 99% of situations, you must include a break to prevent bugs.
Practical Example
Switch statements are excellent for returning specific values based on enumeration-like strings, such as pricing tiers or status codes.
function billingCost(plan) {
switch (plan) {
case "basic":
return 10.0;
case "pro":
return 20.0;
case "enterprise":
return 50.0;
default:
return 0.0;
}
}
console.log(`The cost for a basic plan is $${billingCost("basic").toFixed(2)}`);
console.log(`The cost for a pro plan is $${billingCost("pro").toFixed(2)}`);
console.log(`The cost for an enterprise plan is $${billingCost("enterprise").toFixed(2)}`);