JavaScript/Reserved words/switch

From Wikibooks, open books for an open world
Jump to navigation Jump to search
Previous: super Reserved words Next: synchronized

The switch keyword[edit | edit source]

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".

Examples[edit | edit source]

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


Previous: super Reserved words Next: synchronized