HTML and CSS Reference
In-Depth Information
This code provides the “proceed” instruction when the color is green OR yellow.
When using the logical OR operator in an if statement, the JavaScript engine knows that it can
proceed if any of the statements are true. As such, it evaluates the expressions from left to
right until it finds one that's true. As soon as it does, it won't evaluate any further expressions
but will immediately jump into the true code block. In the preceding example, if the back-
ground is green, the check for whether the background is yellow would never be evaluated.
Structuring code this way is syntactically correct. However, lengthy if statements can
prove difficult to read and even harder to maintain. If your if statements are becoming quite
long—for example, if the previous code example had to test for 15 different colors—a switch
statement might be more appropriate.
Using switch statements
The switch statement provides a construct in which you can test a list of values for equality (as
with the == operator). The following example demonstrates a switch statement:
switch ( {
case 'yellow':
alert('slow down');
case 'green':
case 'red':
alert('unknown condition');
The switch statement consists of several parts. The first is the switch keyword itself,
followed by parentheses surrounding an expression to evaluate. This particular example
evaluates the background color of the canvas element.
Following the switch line is a series of case statements enclosed in braces. The case state-
ment provides the values to evaluate against. This example provides three cases to evaluate:
one for each of the possible red, green, and yellow background colors.
Each case statement contains a required break keyword. This keyword denotes the end of
that particular case statement. Only the first case that evaluates to true in a switch statement
will be processed. Omitting the break keyword will cause unexpected behavior.
The last piece of the switch statement is the optional default keyword, which serves as a
failsafe. If none of the case statements evaluate to true, the default statement provides a way
to handle the situation. You might not want to take any action when none of the case state-
ments evaluates to true—in which case you can omit the default statement. However, it does
Search WWH ::

Custom Search