switch case

Tests a condition against any number of case conditions.


Break must be used to terminate the switch, or the next statement will be executed.


A default case is utilised for when no condition is met.


This example asks the user to enter a value in a dialogue box and then checks it against the values in the switch case code block:

	<script type="text/javascript">
			var value = prompt("Please enter a value between 1 and 5: ", "Please enter your number here.");

			switch (value) {
				case '1':document.write("You entered 1");

				case '2':document.write("You entered 2");

				case '3':document.write("You entered 3");

				case '4':document.write("You entered 4");

				case '5':document.write("You entered 5");

				default: document.write("Unknown value!");

Save & refresh browser:

You entered 5

Leave a Reply