Explanation of switch statement usage in JavaScript
This article describes how to use the switch statement in JavaScript. It is the basic knowledge in JS learning. For more information, see
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.
?
1 2 3 4 5 6 7 8 9 10 11 |
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:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<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:
?
1 2 3 |
Entering switch block Good job Exiting switch block |
Example:
Consider this case if you do not use the break statement:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<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:
?
1 2 3 4 5 6 7 8 |
Entering switch block Good job Pretty good Passed Not so good Failed Unknown grade Exiting switch block |