Switch Case command in JavaScript
You can use multiple if ... else ... if statements as in the previous chapter to make a multiple choice branch. However, it is always not the best solution, especially when all branches depend on the value of a single variable.
You can use multiple if . else . if statements as in the previous post to make a branch of multiple choices. However, it is not always the best solution, especially when all branches depend on the value of a single variable.
Starting with JavaScript 1.2, you can use a switch command to correctly handle this situation, and it's actually more efficient than repeating if . else if statements .
Implementation diagram
The following diagram explains the switch-case command to work:
Syntax
The goal of a switch command is to provide an expression to estimate and several different commands to execute on the value of the expression. The interpreter checks each case - the case with the value of the expression until a match is found. If there is no match, a default condition - will be used by default .
switch ( expression ) { case condition 1 : statement ( s ) break ; case condition 2 : statement ( s ) break ; . case condition n : statement ( s ) break ; default : statement ( s ) }
Break command instructs the end of each specific case. If they are omitted, the interpreter will continue to execute each instruction in each of the following cases.
We will discuss the break command in the Loop control chapter.
For example
Try the following example to execute the switch-case command