The Power of Javascript: Controlling the Execution of the Script - The switch statement
(Page 5 of 6 )
In the last example we have used more than one else if statement inside the if/else structure to test the variable someText with more than one value, then if a match is found the expression evaluates to true, and this else if statement executes its block. This is fine, but Javascript supports the more suitable statement for this situation, the switch statement. The switch statement is useful when we want to check a given variable against multiple values and execute a different block of code depending on the value of the variable. The syntax of the switch statement is complex because it's divided into case sections of the possible values for the variable in question, so let's take a look.
switch(variable)
{
case value1:
statement 1;
statement 2;
statement 3;
break;
case value2:
statement 1;
statement 2;
statement 3;
break;
case value3:
statement 1;
statement 2;
statement 3;
break;
default:
statement 1;
statement 2;
statement 3;
break;
}
As you can see, the switch block is made up of sections, and each of them begins with the keyword case (except for the last section, which we will talk about shortly) followed by a string or numerical value, followed by a colon, then the group of statements, then the keyword break and a semicolon. The interpreter produces the value of the variable between the switch's parentheses, then goes to the first case section and evaluates this section's value. If it's the same as the switch variable's value, it executes this section's statements until it encounters the keyword break, which terminates the execution of the switch statement and executes the first statement in the script following it.
As you can see, the case value: and the break; is much more like a delimiter for each section, because all of the sections exist in one big code block. We are going to use the keyword break in the next article, in which you will really grasp its use, but for now just think of it as a way to exit the switch statement. The last section is labeled default because it's the default section that will execute if no match is found. Normally the interpreter goes to the next case section until a match is found or until the default section. This means that the default section is similar to the else block in the if/else structure. Let's modify our example to use switch instead of multiple else if statements.
Next: The switch example >>
More JavaScript Articles
More By Michael Youssef