JS: Switch Statement
Switch Statement
- The switch statement compares a value to a sequence of values, one by one, in order.
- When a match is found, code start to run from that branch, and continues to run other branches after it.
- Switch-statement uses the Triple Equal Operator to test equality.
π WARNING: switch-statement does fall-through.
It'll jump to a matching point and run all of the rest of case branches without testing.
Think of JavaScript switch as goto.
Add break
if you want it to exit.
π‘ TIP: switch is not useful. It is not a replacement for if-else chain, because it only compares a value, you cannot give it a general true/false expression.
// example of switch statement const x = "a"; switch (x) { case "w": console.log("is w"); break; // without break, it'll continue to run rest case branches without testing case "a": console.log("is a"); break; case 3: console.log("is 3"); break; default: console.log("none of the above"); }