90 likes | 105 Views
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.
E N D
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.
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 …
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.
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.
switch Statement – General Form switch(variable) { case value1: //Block for value1 break; default: //Block for default }
Take the next few minutes to examine the file called switchCase_01.html.
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 …
Summary • Each case block must end with a break statement. • It's considered good programming to include a default block after all case blocks.