Helping ordinary people create extraordinary websites!
GET OUR NEWSLETTER
Your Email:
 

Essential Javascript -- A Javascript Tutorial

By Patrick Hunlock
2007-12-02


JavaScript Conditionals: SWITCH

If you're going to be doing a large number of tests, it makes sense to use a switch statement instead of nested ifs. Switches in javascript are quite powerful, allowing evaluations on both the switch and the case.

var x=5;
switch (x) {
   
case 1: alert('x is equal to 1!'; break;
   
case 2: alert('x is equal to 2!'; break;
   
case 5: alert('x is equal to 5!'; break;
   
default: alert("x isn't 1, 2 or 5!");
}

Note that if you omit the break statement that ALL of the code to the end of the switch statement will be executed. So if x is actually equal to 5 and there is no break statement, an alert for "x is equal to 5" will appear as well as an alert for "x isn't 1,2, or 5!".

Sometimes it makes more sense to do the evaluation in the case statement itself. In this case you'd use true, false, or an expression which evaluates to true or false in the switch statement.

var x=5;
switch (true) {
   
case (x==1): alert('x is equal to 1!'; break;
   
case (x==2): alert('x is equal to 2!'; break;
   
case (x==5): alert('x is equal to 5!'; break;
   
default: alert("x isn't 1, 2 or 5!");
}



Tutorial Pages:
» Essential Javascript -- A Javascript Tutorial
» Getting Started
» In-Line Javascript
» External Javascript
» Javascript is case sensitive
» Output (writeln)
» Output (alert)
» Output (getElementById)
» Input (One Click To Rule Them All)
» Input (User Input)
» Javascript is an Event Driven Language
» Comments
» Variables
» Variable Scope
» Special Keywords
» Arithmetic Operators
» Logical and Comparison Operators
» JavaScript Conditionals: IF
» JavaScript Conditionals: SWITCH
» JavaScript Conditionals: Shorthand Assignment
» JavaScript Conditionals: Ternary Operators
» JavaScript Loops: FOR
» JavaScript Loops: FOR/IN
» JavaScript Loops: WHILE
» Bringing It All Together
» DHTML: Dynamic HTML
» Conclusion


copyright © 2006, 2007 by Patrick Hunlock


 | Bookmark
Related Tutorials:
» JavaScript Debugging Techniques with Firebug
» Striped Tables Using JavaScript
» Opening PDFs in a New Window with JavaScript
» Submit Forms Conditionally using JavaScript
» How to Setup a Randomising Function
» Introduction to JavaScript Tutorial

Advertise with Us!


Tutorials Scripts Web Hosting Developer Manuals
Resources