Use switch to evaluate simple multiple conditionals, instead of using several if else.
<html>
<body>
<script>
color = "yellow"
switch (color) {
case "red":
alert("I'm red like a pepper.")
break
case "yellow":
alert("I'm yellow like a banana.")
break
case "green":
alert("I'm green like... grass!")
break
default:
alert("Illegal color")
}
</script>
</body>
</html>
Warning: don't forget the
break!
Always include a
default. If all conditionals are evaluated to false, the
switch will enter on the
default. This is VERY important.
The US Telephony system was once shutdown for hours just because of a missing default
Putting several conditionals together
<html>
<body>
<script>
character = "e"
switch (character) {
case "a":
case "e":
case "i":
case "o":
case "u":
alert("Vowel")
break
default:
alert("Another character.")
}
</script>
</body>
</html>
Simple example why we use (or don't) the
break