"switch ... case" Statement Example

This section provides a JavaScript tutorial example showing how to write a 'switch ... case' statement.

To help you understand how "switch ... case" statements work, I wrote the following the JavaScript tutorial example, Switch_Case_Statements.html:

<html>
<!-- Switch_Case_Statements.html
   Copyright (c) 2002 HerongYang.com. All Rights Reserved.
-->
<head><title>Switch Case Statements</title></head>
<body>
<pre>
<script type="text/javascript">

// Switch statement with a numeric expression
   var week_day = 4;
   var day, open_hours;
   switch (week_day) {

      case 0:
         day = "Sunday";
         open_hours = "closed";
         break;

      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
         day = "a weekday";
         open_hours = "open from 9:00am to 9:00pm";
         break;

      case 6:
         day = "unknown";
         open_hours = "open from 9:00am to 5:00pm";
         break;

      default:
         day = "unknown"
         open_hours = "undefined";
   }
   document.write('\n');
   document.write("Today is " + day + ".\n");
   document.write("The library is " + open_hours + ".\n");
</script>
</pre>
</body>
</html>

The output of this sample JavaScript is:


Today is a weekday.
The library is open from 9:00am to 9:00pm.

Table of Contents

 About This 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

 AJAX (Asynchronous JavaScript And XML)

 References

 Full Version in PDF/EPUB