20·6
2016
Switch works like if/else but instead of writing multiple entries in curly brackets it allows us to create something akin to a css definition list, with a term and a definition. Definition lists look something like this:
<dl> // definition list
<dt>data term</dt> // the term to be defined
<dl>data definition</dl> // the term's definition
... more term please
</dl>
The switch format is almost exactly the same. It has a container (switch), a parameter (case), and a function that ends with break:
. The switch has one extra item though, an option when none of the cases match the input parameter. Here's a simple example:
switch () {
case 'one' :
do something;
break;
case 'two' :
... more things here
default:’
do something when nothing matches;
}
Here's a simple switch in action.
var woodChuck = prompt("How much wood would a wood chuck chuck, if a wood chuck would chuck wood","A bundle, a stack or a cord?");
switch(woodChuck) {
case('bundle'):
console.log("You're a lazy wood chucker, aren't you?");
break;
case('stack'):
console.log("Not too shabby; enough for one night by the fireplace");
break;
case('cord'):
console.log("That's a busy wood chucker! Send some wood this way.");
break;
default:
console.log("Chuck Norris thinks you're not really trying; Chuck's not happy.");
}