Bem-vindo ao JavaScript Tutorial
Previous topic/Tópico anterior
Next topic/Próximo tópico
07 - switch selector expressions

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

Previous topic/Tópico anterior
Next topic/Próximo tópico
[ Voltar ]


© 2005 JavaScript Tutorial Brasil
Proibida a cópia ou distribuição integral ou parcial não-autorizada
Unauthorized integral or partial distribution or reproduction is forbidden
Patrocínio - Assistência Técnica de Calculadoras HP CSCenter