JavaScript Making Decisions

Combining Case Clauses Together

You may wonder why we need identifiers for both the start and end of each of the cases. The reason is that the code to be run when for a given case does not automatically stop at the point where the next case starts. It always continues through to the next break statement.

This allows us to simplify our processing where we want to perform the same processing for two or more cases. We can list each of these case statements one after the other with no code in between. The code that all of them will run follows after the last case. The end of the code is identified by a single break statement.

case 1:
case 2:
case 3:
   answer = "value is 1, 2, or 3";
case 4: . . .

You should always group your code together like this so that each time that you have code within the switch statement that is followed by another case that the code ends with a break statement to stop it falling through.

There may be rare situations where code can be made far more efficient by actually allowing the code to fall through past case labels. Unless doing so provides major efficiency improvements to the code, the additional maintenance issues that such code can cause will outweigh the benefits that could be gained. If you do have a situation where you want to allow code to fall through then you should make it very clear in your code that this action is deliberate and that it is not simply that a break statement has been accidentally left out.

What We Have Learnt

In this tutorial series we have looked at how JavaScript can make decisions as to which code needs to be run by comparing values. The two statements that we use to do this are if and switch. We also ooked at how to make our code more efficient by nesting statements, adding else or default clauses, or by using an alternative syntax to embed a decision directly into an assignment statement.

go to previous section


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow