You are on page 1of 3

JavaScript Programming Programming Languages Web Development 

JavaScript Switch Case Control Statements


 October 21, 2018  Tanmay Sakpal  0 Comments javascript swith case, switch case control statements, switch case in javascript
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:

1 switch (expression)
2{
3     case value1:
4         statement1;
5         break;
6     case value2:
7         statement2;
8         break;
9     .
10    .
11    case valueN:
12        statementN;
13        break;
14    default:
15        statementDefault;
16}
 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 :
Program Example :
1 <html>
2 <head>
3 <title>IF-Else if - Else Control Statments in javascript</title>
4 <script type="text/javascript">
5 /*Q1) Find day of week by accepting its number. eg. 1-> sunday, 2-> monday etc*/

7 var x = 3;
8 switch(x)
9{
10case 0:
11document.writeln("<h1>Sunday</h1>");
12break;
13case 1:
14document.writeln("<h1>Monday</h1>");
15break;
16case 2:
17document.writeln("<h1>Tuesday</h1>");
18break;
19case 3:
20document.writeln("<h1>Wednesday</h1>");
21break;
22case 4:
23document.writeln("<h1>Thursday</h1>");
24break;
25case 5:
26document.writeln("<h1>Friday</h1>");
27break;
28case 6:
29document.writeln("<h1>Saturday</h1>");
30break;
31default:
32document.writeln("<h1>Enter correct value</h1>");
33}
34</script>
35</head>
36<body>
37</body>
38</html>
39
40
Output :

1Wednesday

You might also like