Advanced Conditional Statements JS Home << JS Advanced << Advanced Conditional Statements
This lesson is about using the switch....case....default
construct to give us a more elegant approach to multiple condition testing of an expression than repeated
else...if
statements. These were described in JavaScripts Intermediate Tutorials - Lesson 3 - Conditional Statements.
We also examine the Conditional special operator and how we use it.
The switch....case....default
Construct
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.
Let's look at an example of this trio of statements to get a feel for the mechanics.
// 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');
}
The Conditional Special Operator
The Conditional special operator takes three operands and is often used as a shortcut replacement for the
if....else
construct. The operator consists of a condition and two expressions. The value of the first expression
is returned if the condition evaluates to true
. The value of the second expression is returned if the condition evaluates to false
.
Following is an example of the Conditional special operator.
// The conditional operator.
var aBoolean = 'true';
alert((aBoolean == 'true' ? 'Evalutes to true' : 'Evalutes to false'));
alert((aBoolean == 'false' ? 'Evalutes to true' : 'Evalutes to false'));}
Lesson 1 Complete
In this lesson we look at the switch....case....default
construct and the Conditional special operator.
Related Tutorials
JavaScripts Intermediate Tutorials - Lesson 3 - Conditional Statements
Reference
JavaScript Reference - switch....case....default
constructor
JavaScript Reference - Conditional
special operator