1. Computing & Technology

JavaScript By Example

12. Switch - Grouping Case

From , former About.com Guide

In the prior example introducing the switch statement I said that it is poor coding practice to allow the code to fall through. There is one situation though where falling through is both appropriate and also clear that it is intentional. This situation arises where you want the exact same code to run for several different values.

p>By placing the case labels immediately one after the other with no code at all in between them the code following the last of them will be what gets run whenever the field matches any of the specified cases.

Note that to test this example try adding a ? followed by a colour to the end of the address of the page - example12.html?red

HTML


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example 12</title>
</head>
<body>
<div id="ex"></div>
<script type="text/javascript" src="example12.js"></script>
</body>
</html>

JavaScript


var colour, code;
colour = window.location.search.substring(1);
switch (colour) {
  case 'red':
  case 'green':
  case 'blue':

    code = 'Primary Colour';
    break;
  case 'cyan':
  case 'magenta':
  case 'yellow':

    code = 'Secondary Colour';
    break;
  default:
    code = 'unknown';
}
document.getElementById('ex').innerHTML = code;

©2012 About.com. All rights reserved.

A part of The New York Times Company.