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

"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) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<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.

Sections in This Chapter

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

Dr. Herong Yang, updated in 2008
"switch ... case" Statement Example