|
JavaScript Home
JavaScript Tutorial Home Basic JavaScriptIntroductionHow to Enable JavaScript JavaScript Syntax External JavaScript File JavaScript Operators JavaScript Variables JavaScript Functions JavaScript Events JavaScript If Statements JavaScript Switch Statements JavaScript While Loop JavaScript For Loop JavaScript Try Catch JavaScript Escape Characters JavaScript Void(0) Advanced JavaScriptJavaScript CookiesJavaScript Date and Time JavaScript Arrays Two Dimensional Arrays JavaScript Summary JavaScript ReferenceJavaScript Reserved WordsJavaScript Event Handlers JavaScript Date and Time Functions JavaScript Code LibraryJavaScript Dropdown MenuJavaScript Print JavaScript Alert Box JavaScript Status Bar Messages Image Rollovers Popup Windows JavaScript Redirect Timed JavaScript Redirect JavaScript Refresh Page Timed JavaScript Redirect Got a MySpace Page?Get "www.yourname.com" for your MySpace page. Learn how >>. |
JavaScript Switch StatementIn the previous lesson about JavaScript If statements, we learnt that we can use an If Else If statement to test for multiple conditions, then output a different result for each condition. For example, if the variable "myColor" was equal to "Blue", we could output one message. If it is "Red" we could output another etc Another way of doing this is to use the JavaScript Switch statement. An advantage of using the switch statement is that it uses less code, which is better if you have a lot of conditions that you need to check for. Example Switch statement:Here, we will re-write the last example in the previous lesson into a switch statement.
The resulting output: Exlanation of codeWe started by declaring a variable called "myColor" and setting it to "Red". We then opened a switch statement, passing in the variable we want to test (myColor). This is followed by a set of "cases" within curly braces. We add a "default" condition, which is only executed if none of the above cases are true. It's important to use "break" after each case - this prevents the code from running into the next case.
Enjoy this website?
Oh, and thank you for supporting Quackit! |
FREE Hosting!With every domain name you register with ZappyHost, you get FREE (ad supported) hosting.PLUS you get:
Featured Template:
(Build your websites in minutes!) |