1 / 9

Switch Statements

Learn how to use switch statements in JavaScript to test a single variable against multiple possible values, with case blocks and a default case. Understand the syntax and usage of switch statements.

barnesl
Download Presentation

Switch Statements

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Switch Statements

  2. Goals By the end of this lecture you should … • Understand how to program switch statements with case blocks to test a single variable against multiple possible values.

  3. Nesting Decision Structures? • Of course, JavaScript allows us to program nested if-then-else structures to deal with multiple possible situations. • However, sometimes it is easier to use a switch statement instead, especially if you are testing a single variable against multiple possible values …

  4. The switch Statement • The switch statement allows us to test a single variable against multiple possible values. • We test each possible value in case blocks, each of which includes a value against which we test and an executable block, executed if the value matches.

  5. More on the switch Statement • We can have any number of cases. Each case's executable block needs to contain a break statement at the end in order to "break out" of the switch structure, if we found a matching value. • It's a good idea to include a default case at the end of the switch statement.

  6. switch Statement – General Form switch(variable) { case value1: //Block for value1 break; default: //Block for default }

  7. Take the next few minutes to examine the file called switchCase_01.html.

  8. Summary • We can use switch statements to test single variables against multiple possible values. • case blocks provide executable blocks for matching values in a switch statement. continued …

  9. Summary • Each case block must end with a break statement. • It's considered good programming to include a default block after all case blocks.

More Related