Learning JavaScript tutorial – JavaScript switch Statement
JavaScript switch statement control the flow of program execution via a multiway branch. When we need execute a statement block depending on the value of a single variable; JavaScript switch Statement is the best alternative to JavaScript if Condition Statement to it handles the situation more efficiently than repeated if statements.
JavaScript switch Statement Syntax
switch (conditional expression)
{
case condition 1:
statement block executed if condition 1 is true(satisfied).
break;
case condition 2:
statement block executed if condition 1 is true(satisfied).
break;
.
.
.
case condition n:
statement block executed if condition n is true(satisfied).
break;
default:
statement block executed if no condition is true(satisfied).
break;
}
When a switch executes, it first computes the value of conditional expression and then looks for a case label whcih matches that value of the conditional expression. After the sucessful match with the condition in the case clause; the statement block followed it get executed. If nothing matches with the conditions in the case clause, a default condition is get executed.

Switch Condition Statement flowchart
Note, the break keyword used at the end of each case clause. break helps the switch statement to terminate and prevent execution of the statement block in the next case. The case clauses in a switch statement specify only the starting point of the desired code; break helps to specify the ending point of the case clauses. If you miss to use the break statements, a switch statement begins executing its block of code at the case label that matches with the value of its conditional expression and continues executing all the statements until it reaches to the end.
<script type="text/javascript">
var currentDate=new Date();
var sDay;
switch(currentDate.getDay()){
case 0:sDay="Sunday";break;
case 1:sDay="Monday";break;
case 2:sDay="Tuesday";break;
case 3:sDay="Wednesday";break;
case 4:sDay="Thursday";break;
case 5:sDay="Friday";break;
case 6:sDay="Saturday";break;
}
alert("Today is "+sDay);
</script>





Comments
No comments yet.
Leave a comment