Thursday 28 February 2013

JavaScript : Switch Statement


Switch statement 

Description

The switch statement allows to make a decision from the number of choices.
If a match is found to a case label, the program executes the associated statement.
If no match is found with any of the case statements, only the statements following the default are executed. 
If no default statement is found, the program continues execution at the statement following the end of switch.
Note that switch statement is almost similar to a series of if statements on the same expression.

Syntax

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

Parameters

expression : Value matched against label.
label : An Identifier to be matched against expression.
statements : Group of statements that are executed once if expression matches label.

Example

In the following example switch statment is used to display the marks range against a particular grade.

HTML Code

  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4. <meta charset=utf-8>  
  5. <title>JavaScript Switch statement : Example-1</title>  
  6. <link rel="stylesheet" type="text/css" href="example.css">  
  7. </head>  
  8. <body>  
  9. <h1>JavaScript : switch statement</h1>  
  10. <form name="form1" action ="#">  
  11. Input Grade type : <input type="text" name="text1" value="A" />  
  12. <br /><br />  
  13. <input type="button" value="Marks check"  
  14. onclick='marksgrade()' />  
  15. </form>  
  16. <script src="switch-statement-example1.js"></script>  
  17. </body>  
  18. </html>  

JS Code

  1. function marksgrade()  
  2. {  
  3. grade = document.form1.text1.value;  
  4. switch (grade)  
  5. {  
  6. case 'A+':  
  7.   alert("Marks >= 90");  
  8.   break;  
  9. case 'A':  
  10.   alert("Marks [ >= 80 and <90 ]");  
  11.   break;  
  12. case 'B+':  
  13.   alert("Marks [ >= 70 and <80 ]");  
  14.   break;  
  15. case 'B':  
  16.   alert("Marks [ >= 60 and <70 ]");  
  17.   break;  
  18. case 'C':  
  19.   alert("Marks < 60");  
  20.   break;  
  21. default:  
  22.   alert("Wrong grade.........");  
  23. }  
  24. }  

Practice the example online


No comments:

Post a Comment