JavaScript – Switch Case

In our previous article we learned about decision making statement if-else. switch case statement is also used for decision making purposes. It’s a multi-way branch statement and in some cases switch case statement is more convenient over if-else statements, like when we want to test a variable for hundred different values and according to those values we want to execute some statement, for this switch-case will be more efficient and fast method then the if-else.

Flow Chart

Switch Case Flow

Syntax

switch(expression) {
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
default:
code to be executed;
}

Example:

<html>
<script>
var day = 4;
switch (day) {
case 1:
document.write(“Monday”);
break;
case 2:
document.write(“Tuesday”);
break;
case 3:
document.write(“Wednesday”);
break;
case 4:
document.write(“Thursday”);
break;
case 5:
document.write(“Friday”);
break;
case 6:
document.write(“Saturday”);
break;
case 7:
document.write(“Sunday”);
break;
default:
document.write(“Not a Day!”);
}
</script>
</html>


Output:
Thursday


Break statements play a major role in switch-case statements to display only 1 statement as per value and exit.

Try the same code without any break statement.

<html>
<script>
var day = 4;
switch (day) {
case 1:
document.write(“Monday”);
case 2:
document.write(“Tuesday”);
case 3:
document.write(“Wednesday”);
case 4:
document.write(“Thursday”);
case 5:
document.write(“Friday”);
case 6:
document.write(“Saturday”);
case 7:
document.write(“Sunday”);
default:
document.write(“Not a Day!”);
}
</script>
</html>


Output:
ThursdayFridaySaturdaySundayNot a Day!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.