Switch Statement in Javascript

Using switch Statement.

  • A swich statement has the form:
      switch (expression) {
        case (expression1): // Start here if expression == expression1
          statement;
          break;            // Jump outof switch statement
        case (expression2): // Start here if expression == expression2
          statement;
          break;            // Jump outof switch statement
        case (expression3): // Start here if expression == expression3  
          statement;
          break;            // Jump outof switch statement
        default:            // Start here if No match        
          statement;
      }

    Where :
    • Expression is any legal Javascript expression that that returns a value.
    • Statements are any legal Javascript statements or block of statements that is been evaluated.
    • If one of the case expessions matches the swicth expression, program execution jumps to those statements and continues to the end of the switch block unless a break statement is encountered, which ends the switch block.
    • If nothing matches, execution branches to the optional default statement.
    • If no default exists and no matching case expression exist, execution falls through the switch statement and the statement ends.
    <script type="text/javascript">
      var sum=prompt("Enter a hole number; 1,2 or 3");
      switch (sum) {
        case '1': // Start here if expression == expression1
          document.write("Number is exact 1");
          break;            // Jump outof switch statement
        case '2': // Start here if expression == expression2
          document.write("Number is exact 2");
          break;            // Jump outof switch statement
        case '3': // Start here if expression == expression3
          document.write("Number is exact 3");
          break;            // Jump outof switch statement
        default:            // Start here if No match
          document.write("The number is not valid!");
      }
    </script>

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.