HTML and CSS Reference
In-Depth Information
enable you to handle the scenario where one of the conditions should have been reached but
wasn't, possibly due to bad data being passed into a method or a valid case being missed.
Including a default to account for both of those scenarios is good practice.
You can't force logical flow in a
switch
statement to move from one case to the next by
omitting the
break
keyword; in other words, only one conditional block is processed within a
switch
statement. This means that logically, you can't use the AND logical operator. However,
you can leverage the OR logical operator. The following code demonstrates a case in which
you want the same code to run for both the green and yellow background conditions:
switch (canvas.style.backgroundColor) {
case 'yellow':
case 'green':
alert('proceed');
break;
case 'red':
alert('stop');
break;
default:
alert('unknown condition');
break;
}
In this code, multiple
case
statements are stacked onto each other. If any of the stacked
case
statements evaluates to true, the code block following that
case
statement is processed, thus
implying a logical OR. You don't need to explicitly use the logical OR operator (||) to leverage
logical OR semantics.
IMPORTANT
A VALID
SWITCH
STATEMENT
The values used in the
case
statement for the purposes of the evaluation must be ex-
pressed as a constant. For example, switching on an integer value to determine whether
it's divisible by another number won't work because the case would require an expression
instead of a constant value. For example,
case x / 10:
would be an invalid
case
statement.
However, the
switch
statement itself can accept an expression to evaluate against all cases
inside the switch block.
Using
ternary operators
The ternary operator is essentially a shorthand mechanism for an
if
statement. The syntax of
the ternary operation is
<
expression
> ? <
true part
>: <
false part
>
When the expression evaluates to true, the true part runs; otherwise, the false part runs.
This code demonstrates using the ternary operator to check the background color of the
canvas:
canvas.style.backgroundColor == 'green' ? document.write('proceed') :
document.write('stop');
Search WWH ::
Custom Search