< JavaScript < Reserved words

The switch keyword

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

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;
  }
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.