The Case Statement

The main method for making decisions in programming is to use the if statement. The if statement is a very powerful command but there are certain instances when its power is not required.  The alternative to if when this happens is to use the case statement.

The format of the case statement in JavaScript is:

switch (number)
{ // begin switch

case 1:
{ // begin case 1
Program statement(s) ;
break ;
} // end case 1

case 2:
{ // begin case 2
Program Statement(s) ;
break ;
} // end case 2

case 3:
{ // begin case 3
Program Statement(s) ;
break ;
} // end case 3

default :
{ // begin default
Program Statements that will be carried out if the number is not a 1, 2 or 3.
} // end default

} // end switch

The default part of the case statement operates in a similar way to the else part of the if statement. This is an optional part of the case statement and could be left out if all of the case values are covered. However, the break statements used inside the brackets for each case must be included or else all of the code will be carried out.

Next: Case Statement (Integer)