switch....case....default constructS2C Home « Statements « 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) {
   case label1:
      statements1
      [break;]
   case label2:
      statements2
      [break;]
   ...
   case labelN:
      statementsN
      [break;]
   default:
      defaultStatements
      [break;]
}
Creates a loop structure with three optional expressions.

Parameters

Parameter Description
expressionAn expression to be evaluated against each label.
label1...labelNThe case value to match againt the expression.
statements1...statementsNThe statements to be executed when the associated case value is matched.
defaultStatementsThe 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');
}

Press the button below to action the above code:


Related Tutorials

JavaScript Advanced Tutorials - Lesson 1 - Advanced Conditional Statements

go to home page Homepage go to top of page Top