Technology Programming

Understanding "Switch" Statements in Javascript

An if/else statement allows for just two alternate paths. To handle more than that you need to either nest if statements inside of one another or use a switch statement. What a switch statement does it to take a single field and compare it to a number of different values (the equivalent of a whole series of 'value' === field tests).

The field to be tested is specified in the switch statement itself and all of the code for the switch is contained within a block.

Each individual value you want to test for is specified as a label after the keyword 'case' and that is then followed by the statements for the path that is to be followed when that value is in the field. All of the following statements are then run until a break statement is reached at which point the processing jumps to the next statement after the end of the block. A default label at the end of the block provides a catchall for when the field contains any value other than those specifically mentioned in a case.

Note that if no break is specified then the code will fall through and continue running all of the following statements. This can lead to errors where the code falls though by accident and it is therefore considered poor coding practice to allow the code to fall through. At the very least you should comment where the fallthrough is deliberate so that it does not get misidentified as the possible cause of an error.

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

HTML


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

JavaScript


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

    code = '#ff0000';
    break;
  case 'green':
    code = '#00ff00';
    break;
  case 'blue':
    code = '#0000ff';
    break;
  default:
    code = 'unknown';
}
document.getElementById('ex').innerHTML = code;

Related posts "Technology : Programming"

The Importance Of Having a WordPress Business Theme

Programming

Website Design Is Necessary For Your Website

Programming

The Most effective On line Paid Survey Evaluation

Programming

Adelaide SEO - Links And Keywords, How Should They Be Used

Programming

C Programming Compilers for Microcontrollers

Programming

How Should A DJ Make Music Logo That Is Distinct And Cool?

Programming

Call to Action Concepts for Small Businesses

Programming

Microsoft Access Databases in Office 365

Programming

Why web design is crucial for producing world class websites

Programming

Leave a Comment