Welcome to Bucaro TecHelp!

Bucaro TecHelp
HTTPS Encryption not required because no account numbers or
personal information is ever requested or accepted by this site

About Bucaro TecHelp About BTH User Agreement User Agreement Privacy Policy Privacy Site Map Site Map Contact Bucaro TecHelp Contact RSS News Feeds News Feeds

The switch/case Structure

The switch/case structure lets you match a variable's or expression's value to a number of values and then execute code when a match is found. A description of the switch/case structure is shown below.

switch(expression)
{
case (value):
  statements;
  break;
case (value):
  statements;
  break;
default:
  statements;
}

The variable or expression is placed in brackets after the switch statement. The body of the structure contains one or more comparison values in brackets case statements. Each case section defines a block of code to be executed if its value matches the value in the switch statement.

Note that the last line of each case branch (except the last one) is the break command. If you omit the break command, the code in every case section following the one with the matching value will be executed until a break command is found. The break command causes execution to break out of the switch/case structure.

The omission of the break command might be an error, but sometimes it is used as a deliberate method of program flow control.

Note the default branch at the end of the structure. Use the default section for code to execute if none of the case values are found to match.

The example below shows a switch/case structure which branches based upon matching the value of a variable placed in the switch statement.

switch(a)
{
case(1):
  alert("a = 1");
  break;
case(2):
  alert("a = 2");
  break;
case(3):
  alert("a = 3");
}

RSS Feed RSS Feed

Follow Stephen Bucaro Follow @Stephen Bucaro


Fire HD
[Site User Agreement] [Privacy Policy] [Site map] [Search This Site] [Contact Form]
Copyright©2001-2024 Bucaro TecHelp 13771 N Fountain Hills Blvd Suite 114-248 Fountain Hills, AZ 85268