Documentation
Back to website >

switch (JScript)

The"switch" instruction checks the specified expression for conformity with the marks specified in case. If a case mark applies, all statements after the case mark are processed until the end of the switch block or a break statement is reached. If none of the case marks apply, the default clause is processed.

If the dafault clause is not specified, no statement of the switch block is processed if no case mark applies.

When using the switch statement, make sure that you want all statements to be processed after the first applicable case mark and, if necessary, add a brak statement to each case mark. In this case, it is also useful to place the default statement at the end of the switch block.

Syntax

switch (expression) 
{ 
  case label :
    statement list
  case label :
    statement list
  ...
  default :
    statement list
}

Example

var
  Weekday;

Weekday=3;

switch (weekday)
{
  case 1:
    Result="Monday";
    break;
  case 2:
    Result="Tuesday";
    break;
  case 3:
    Result="Wednesday";
    break;
  case 4:
    Result="Thursday";
    break;
  case 5:
    Result="Friday";
    break;
  case 6:
    Result="Saturday";
    break;
  case 7:
    Result="Sunday";
    break;
  default:
    Result="Unknown";
}

In this example, the day of the week variable is set to the value "3" and the switch application is executed. The mark 3 applies to the comparison tests, so that the value"Wednesday" is assigned to the result variable. The break statement prevents the following marks and thus the statements from being processed. If the break statement would not exist, all statements would be executed after marker 3, so that the variable Result would always have the value "Unknown".