The switch statement in JavaScript performs expression evaluation and runs block code depending on matching case conditions. A series of cases with identical results can share combined code blocks instead of using duplicate code. As a switch exits with a break after running any chosen case, it automatically prevents additional case evaluations. When an expression matches no cases, the default case will execute.
Example: Handling Multiple Cases in a Switch Statement
let day = "Saturday";
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
console.log("It's a weekday.");
break;
case "Saturday":
case "Sunday":
console.log("It's the weekend!");
break;
default:
console.log("Invalid day.");
}
Explanation:
The switch declaration examines the day variable value for assessment.
All weekdays starting from "Monday" through "Friday" follow consistent logic, thus receiving their group execution before triggering the code block of “It's a weekday.”
The statements "It's the weekend!" function once through the grouping of "Saturday" and "Sunday".
The default "Invalid day" message will execute when the day fails to match any previous cases.
By grouping multiple values in cases, the program becomes more readable and reduces duplicate code for similar scenarios.
Learn tips and tricks for learning JavaScript faster,
in this article
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
The switch statement in JavaScript performs expression evaluation and runs block code depending on matching case conditions. A series of cases with identical results can share combined code blocks instead of using duplicate code. As a switch exits with a break after running any chosen case, it automatically prevents additional case evaluations. When an expression matches no cases, the default case will execute.
Example: Handling Multiple Cases in a Switch Statement
Explanation:
By grouping multiple values in cases, the program becomes more readable and reduces duplicate code for similar scenarios.
Learn tips and tricks for learning JavaScript faster, in this article