JavaScript Making Decisions

The DEFAULT Clause

The switch statement in the last tutorial is not quite identical to the series of if/else statements in that tutorial because it doesn't have anything to handle the final else clause. That final else captures all of the values not previously tested for. We don't have to use an if statement with our switch in order to test for this, the switch has a way to handle this specific situation. With the switch statement as we have it so far, the appropriate case will be run when the value is any of those listed. When it is any value apart from one of those the switch simply skips to the next statement.

Where we want to run one or more statements when none of the cases match, we can add one further test into our switch statement. Instead of using the word case followed by a value for this test, we simply use the word default instead. We always place this at the very end of our switch statement.

Adding this to our existing switch statement allows us to exactly duplicate the if statement construct exactly including that final else. The switch statement below is identical in what it does to the nested if statements of the last tutorial.

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;
   default: otherLetter += 1;

As the default clause is always last in the switch statement and since it differs slightly in appearance from the other cases, we can omit the break from the end of this clause.

go to previous section go to next section 


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow