1. Technology
Send to a Friend via Email

Your suggestion is on its way!

An email with a link to:

http://javascript.about.com/od/decisionmaking/a/des13.htm

was emailed to:

Thanks for sharing About.com with others!

JavaScript Making Decisions

13. Combining Case Clauses Together

By

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";
   break;
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 looked 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.

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

  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. Learn Modern JavaScript
  6. 2. Decision Making
  7. JavaScript Combining Case Clauses Together

©2014 About.com. All rights reserved.