JavaScript/Reserved words/switch

Previous: super Reserved words Next: synchronized

The switch keywordEdit

The switch keyword is a control structure that evaluates the expression and compares it with the values in the case clauses. If none match, the default clause is executed.

If there is no break after the end of a case clause or a return, execution continues; otherwise, the switch block is left. It is good programming practice to comment a deliberate "falling through".


Example 1
  switch (type) {
    case 0:
      return "zero";
    case 1:
      result += 7;
      // Falling through!
    case 2:
      result = [2, 3];
      result = null;
Example 2
  switch (color) {
    case "red":
      return 0xFF0000;
    case "green":
      return 0x00FF00;
    case "blue":
      return 0x0000FF;
      return 0x777777;

Previous: super Reserved words Next: synchronized