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 ( {
case 'yellow':
case 'green':
case 'red':
alert('unknown condition');
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.
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: == 'green' ? document.write('proceed') :
Search WWH ::

Custom Search