Creating switch Statements

The JavaScript switch statement is the next step up in decision making after the if statement. You use the switch statement if you want to test a large number of cases and don't want to construct a long ladder of if...else statements.

Here's how it works: You compare a test expression against a number of values. If one of those values matches, the code associated with the value is executed until the JavaScript interpreter finds a break statement. Here's what the switch statement looks like in outline:

switch(test){
    case value1:
          .
          .
          .
        code executed if test matches value1
          .
          .
          .
        break;
    case value2:
          .
          .
          .
        code executed if test matches value2
          .
          .
          .
        break;
    case value3:
          .
          .
          .
        code executed if test matches value3 . . . break; ...

Get Real World XML now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.