Promotic
WikipediaLinkedInYoutubeTwitterFacebook

switch - statement of language JavaScript

Description:
Executes one of several groups of statements, depending on the value of an expression.
Syntax:
switch (testexpression)
{
case value :
  statements
  break;
 
...
 
default:
  statements
  break;
}
 
testexpression - Any numeric or string expression.
statements - One or more statements executed if testexpression matches of value.
default - (optional) One or more statements executed if testexpression doesn't match any of the case clauses.
Note:
If value matches any value case, then the commands following after the case are executed up to the break. If the command break is not present then the process continues to the following case sections - this way it is possible, for example, to merge multiple case sections - see Example1.

Default is used for processing unexpected values of value.

 
For similar purpose in the VBScript language is used the command Select Case.
See also:
Example1:
One portion of commands may belong to multiple values (case 1: and case 2:):
var nVar = 1, sColor;
switch (nVar)
{
case 1:
case 2:
  sColor = "green";
  break;
case 3:
  sColor = "blue";
  break;
default:
  sColor = "black";
  break;
}
Example2:
Commands can be written on a single row:
var nVar = 1, sColor;
switch (nVar)
{
case 1:
case 2: sColor = "green"; break;
case 3: sColor = "blue"; break;
default: sColor = "black"; break;
}
© MICROSYS, spol. s r. o.Tavičská 845/21 703 00 Ostrava-Vítkovice