switch....case....default
construct
JS Home <<
JS Reference <<
switch....case....default
Conditional Statement Construct.
Description
The switch....case....default
construct allow us to evaluate an expression and act accordingly.
The switch
statement is where we put the expression we are going to evaluate. Each case
statement is evaluated against the switch
expression and the statements within
the case
are processed on a match. We have the option to break
from the switch
after this if required. We can also code an optional default
statement,
which can act as a kind of catch all and is normally placed, at the end, after the case
statements.
Syntax
Signature | Description |
---|---|
switch (expression) { | Creates a loop structure that with three optional expressions. |
Parameters
Parameter | Description |
---|---|
expression | An expression to be evaluated against each label. |
label1...labelN | The case value to match againt the expression. |
statements1...statementsN | The statements to be executed when the associated case value is matched. |
defaultStatements | The statements to be executed when no case values are matched. |
Examples
The code below gives examples of using the switch....case....default
statements.
// A switch where a case matches.
var aVariable == 'blue';
switch (aVariable) {
case 'red':
alert('colour is red');
break;
case 'blue':
alert('colour is blue');
break;
case 'yellow':
alert('colour is yellow');
break;
default:
alert('Default as no case matches');
}
// A switch where no case matches.
var aVariable == 'gold';
switch (aVariable) {
case 'red':
alert('colour is red');
break;
case 'blue':
alert('colour is blue');
break;
case 'yellow':
alert('colour is yellow');
break;
default:
alert('Default as no case matches');
}
Related Tutorials
JavaScript Advanced Tutorials - Lesson 1 - Advanced Conditional Statements