JS: Switch Statement

By Xah Lee. Date: .

Switch Statement

πŸ›‘ 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");
}

JavaScript, Conditionals