|
JavaScript Home
JavaScript TutorialIntroductionHow to Enable JavaScript JavaScript Syntax JavaScript Popup Boxes JavaScript and HTML 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) JavaScript Cookies JavaScript Date and Time JavaScript Arrays Two Dimensional Arrays JavaScript innerHTML JavaScript Summary JavaScript ReferenceJavaScript Reserved WordsJavaScript Event Handlers JavaScript Date and Time Functions JavaScript ExamplesList of ExamplesJavaScript Dropdown Menu JavaScript Print JavaScript Alert Box JavaScript Confirm JavaScript Prompt JavaScript Status Bar Messages Image Rollovers Popup Windows JavaScript Redirect Timed JavaScript Redirect JavaScript Refresh Page |
JavaScript Switch StatementIn the previous lesson about JavaScript If statements, we learned 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.
|
Need Website Content?
Get unique, quality digital content for your website.
|