JavaScript Switch Statement
The JavaScript switch statement is a lesser-used case structure of JavaScript. It is similar to use multiple elseif's on the same variable in an if-elseif-else JavaScript structure.
Basic switch Syntax
var x = 10;
switch (x) {
case 5:
// Do something.
case 10:
// Do something else (this will be executed).
case 15:
// Do something else.
}
In this example, we declare the variable x and initialise it to 10. We then have a switch on x. Within a switch statement, the value of the target of the switch statement - in this case, x - is compared against a number of cases, and the code within the block for a case that is true is executed.
For example, here we have
case 10true, as our variable is indeed 10, therefore the code after the
case 10: will be executed.
Default case
Sometimes you will want to take an action if a variable is one of a
number of options, and another action if it is none of those options.
This is done with the default case:
var x = 8;
switch (x) {
case 10:
// Do something.
case 15:
// Do something else.
default:
// This will be executed.
}
If none of the cases in the structure match the value of the variable, the code under the default: will be executed.
Break on case
Consider this example:
var x = 10;
switch (x) {
case 10:
// This will be executed.
x = 15;
case 15:
// This will also be executed.
}
Here, we change the value of the variable in our case code block,
such that it matches the next case as well. In this case, the code in
both code blocks will be executed. We can prevent this with the break instruction:
var x = 10;
switch (x) {
case 10:
// This will be executed.
x = 15;
break;
case 15:
// This will not be executed.
break;
}
A break here functions similarly to a break in an if block; if breaks out of the structure. Generally, you should have a break at the end of all your cases. A break is not required for a default.
Next let's take a look at JavaScript Arrays.
| « Advanced JavaScript | JavaScript Arrays » |

