JavaScript Switch Case Control Statements

You can use multiple if…else…if statements to perform a multiway branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable. Starting with JavaScript 1.2, you can use a switch statement which handles exactly this situation, and it does so more efficiently than repeated if…else if statements.

The switch case statement in JavaScript is also used for decision making purposes. In some cases, using the switch case statement is seen to be more convenient over if-else statements. Consider a situation when we want to test a variable for hundred different values and based on the test we want to execute some task. Using if-else statement for this purpose will be less efficient over switch case statements and also it will make the code look messy.

Syntax:

switch (expression)
{
    case value1:
        statement1;
        break;
    case value2:
        statement2;
        break;
    .
    .
    case valueN:
        statementN;
        break;
    default:
        statementDefault;
}
  • expression can be of type numbers, strings or boolean.
  • The default statement is optional. If the expression passed to switch does not matches with value in any case then the statement under default will be executed.
  • The break statement is used inside the switch to terminate a statement sequence.
  • The break statement is optional. If omitted, execution will continue on into the next case.

Flow Chart Diagram :

switch case statements flow diagram in javascript

Program Example :

<html>
	<head>
 		<title>IF-Else if - Else Control Statments in javascript</title>
		<script type="text/javascript">
			/*Q1) Find day of week by accepting its number. eg. 1-> sunday, 2-> monday etc*/

			var x = 3;
			switch(x)
			{
				
				case 0:
					document.writeln("<h1>Sunday</h1>");
					break;
				case 1:
					document.writeln("<h1>Monday</h1>");
					break;
				case 2:
					document.writeln("<h1>Tuesday</h1>");
					break;
				case 3:
					document.writeln("<h1>Wednesday</h1>");
					break;
				case 4:
					document.writeln("<h1>Thursday</h1>");
					break;
				case 5:
					document.writeln("<h1>Friday</h1>");
					break;
				case 6:
					document.writeln("<h1>Saturday</h1>");
					break;
				default:
				document.writeln("<h1>Enter correct value</h1>");
			}
			
		</script>
	</head>
	<body>
	</body>
</html>

Output :

Wednesday
Watch it on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *