The usage of the switch statement in JavaScript is described in detail.
You can use multiple if... else if statements, such as the previous chapter, to execute multiple branches. However, this is not always the best solution, especially when all branches depend on the value of a single variable.
Starting with JavaScript1.2, you can use it to handle this situation. Using a switch statement is more effective if you do not use the if... else if statement repeatedly.
Syntax
The basic syntax of the switch statement provides an expression to evaluate and calculate several different statements based on the value of the expression for execution. The interpreter checks each condition of the expression value until a match is found. If no match exists, the default condition is used.
switch (expression){ case condition 1: statement(s) break; case condition 2: statement(s) break; ... case condition n: statement(s) break; default: statement(s)}
The interpreter indicated by the break statement ends in a specific situation. If they are omitted, the interpreter continues to execute each statement in each of the following cases.
We will explain the break statement in the loop control chapter.
Example:
The following example illustrates a basic while loop:
<script type="text/javascript"><!--var grade='A';document.write("Entering switch block<br />");switch (grade){ case 'A': document.write("Good job<br />"); break; case 'B': document.write("Pretty good<br />"); break; case 'C': document.write("Passed<br />"); break; case 'D': document.write("Not so good<br />"); break; case 'F': document.write("Failed<br />"); break; default: document.write("Unknown grade<br />")}document.write("Exiting switch block");//--></script>
This produces the following results:
Entering switch blockGood jobExiting switch block
Example:
Consider this case if you do not use the break statement:
<script type="text/javascript"><!--var grade='A';document.write("Entering switch block<br />");switch (grade){ case 'A': document.write("Good job<br />"); case 'B': document.write("Pretty good<br />"); case 'C': document.write("Passed<br />"); case 'D': document.write("Not so good<br />"); case 'F': document.write("Failed<br />"); default: document.write("Unknown grade<br />")}document.write("Exiting switch block");//--></script>
This produces the following results:
Entering switch blockGood jobPretty goodPassedNot so goodFailedUnknown gradeExiting switch block