1. Computing

JavaScript Making Decisions

11. The SWITCH Statement

By

There is another combination of if statements where an alternative notation is available.

We may need to test one variable for a number of different values and run different code depending on which of those values that it has. An example of the code to do this type of testing using if statements is shown here.






if ('a' == letter) {
   a += 1;
} else if ('b' == letter) {
   b += 1;
} else if ('c' == letter) {
   c += 1;
} else if ('d' == letter) {
   d += 1;
} else if ('e' == letter) {
   e += 1;
} else if ('f' == letter) {
   f += 1;
} else {
   otherLetter += 1;
}

This combination comes up frequently in JavaScript. JavaScript provides a shorter and easier to read way of coding tests like this.

This alternative construct is usually called a case statement because almost every programming language that provides it uses the word "case" to define the various values to be compared. In JavaScript the reserved word switch indicates the start of a case statement and each of the individual tests is identified with the reserved word case. A third reserved word break breaks out of the entire statement and jumps to the statement following the end of the switch block. Here is a part of our code from above rewritten to use a case statement in place of most of if statements.


switch (letter) {
   case 'a': a += 1; break;
   case 'b': b += 1; break;
   case 'c': c += 1; break;
   case 'd': d += 1; break;
   case 'e': e += 1; break;
   case 'f': f += 1; break;
}

Note that the last break statement is really redundant since the next statement is after the end of the block in any case but is best included for consistency and to allow additional cases to be easily added to the end of the statement.

As with most JavaScript the actual way that you format the statement is up to you.

All of the statements in these examples end with a semi-colon. The semi-colons to end each statement in JavaScript are optional provided that each statement is on a separate line. It is better to always including the semi-colons to make it clear where each statement ends. Where you have just a short statement to include within each case, including the break statement on the same line as the preceding statement allows us to fit each case on a single line making the entire switch statement much more readable.

This tutorial first appeared on www.felgall.com and is reproduced here with the permission of the author.

Related Video
How to Install a Dimmer Switch
  1. About.com
  2. Computing
  3. JavaScript
  4. Javascript Tutorials
  5. Learn Modern JavaScript
  6. 2. Decision Making
  7. JavaScript SWITCH Statement

©2014 About.com. All rights reserved.