Grammar - Switch Statement
Table of Contents
About
A switch is a multi-way branch.
Articles Related
Fall through behavior
The switch statement has fall through behavior therefore the break is important.
If you omit the break from a case, and that case matches or runs, execution will continue to the next case.
Without break
color = "green"
switch (color) {
case "blue":
console.log("blue");
case "green":
console.log("green");
case "red":
case "orange":
console.log("red or orange");
default:
console.log("default");
}
- Result: You will see all console output from the green case
With ''break'
color = "green"
switch (color) {
case "blue":
console.log("blue");
break;
case "green":
console.log("green");
break;
case "red":
case "orange":
console.log("red or orange");
break;
default:
console.log("default");
}
- Result: you will see only one output