JavaScript Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 2.20

"switch ... case" Statements

This section provides a quick description of the 'switch ... case' statement.

"switch case" statements are alternative ways of executing statements selectively based on certain conditions. A "switch case" statement has the following generic syntax format:

switch (test_expression) {
   case expected_value_1:
      statement_11;
      statement_12;
      ...
      [break;]
   case expected_value_2:
      statement_21;
      statement_22;
      ...
      [break;]
   ...
      ...
   default:
      statement_x1;
      statement_x2;
      ...
      [break;]
}

where "test_expression" is used to generate a test value that will be tested against with expected values specified in "case" clauses. The execution of a "switch case" statement goes like this:

  • "case" clauses are possible execution starting points. Each "case" clause will be visited sequentially from top to bottom.
  • If the expected value of a "case" clause equals to the test value resulted form the switch expression, the execution starts from those statements listed in this "case" clause.
  • Once the execution started, it will continue until a break statement is reached or the end of the "switch" block is reached.
  • The "default" clause is optional. But if it is provided, it will become the execution starting point when all case tests before the "default" clause are failed.

Unlike many other programming languages, JavaScript supports both numeric expression and string expression as the switch test expression.

A tutorial example will be given in the next section showing examples of "switch ... case" statements.

Table of Contents

 About This JavaScript Tutorial Example Book

 Introduction to JavaScript

 ECMAScript Language Specification and JavaScript Dialects

 Data Types, Variables and Expressions

Flow Control Statements

 What Is a Statement?

 Conditional "if" Statements

 Conditional "if" Statement Examples

"switch ... case" Statements

 "switch ... case" Statement Example

 "for" Loop Statements

 "for" Loop Statement Example

 "while" Loop Statements

 "while" Loop Statement Example

 Creating, Accessing, and Manipulating Arrays

 Defining and Calling Functions

 Web Browser Supporting JavaScript

 Server-Side and Client-Side Web Scripting

 Introduction to Objects

 Defining Your Own Object Types

 Inheritance of Properties and Methods through the Prototype Object Chain

 'jrunscript' - JavaScript Shell Command from JDK

 Using Functions as "Function" Objects

 Introduction to Built-in Object Types

 W3C's Document Object Model (DOM) Specifications

 References

 PDF Printing Version

Dr. Herong Yang, updated in 2008
"switch ... case" Statements