HTML and CSS Reference
In-Depth Information
This code processes the code block, and then while an expression is true, continues to
process this code block. The following code segment demonstrates this:
var canvas = document.getElementById("canvas1");
do {
//stop traffic
}while(canvas.styles.backgroundColor == 'red')
In this code segment, the logic to stop traffic runs one time. Then, it evaluates the
expression that checks whether the background of the canvas is red. The loop continues to
run as long as this expression evaluates to
true
.
Short-circuiting the loops
Two mechanisms enable you to short-circuit a loop. The
break
keyword exits the current loop
completely, whereas the
continue
keyword breaks out of the code block and continues to the
next iteration of the loop.
EXAM TIP
The
break
keyword breaks out of only the currently running loop. If the loop containing
the
break
is nested inside another loop, the outer loop continues to iterate as controlled by
its own expression.
Thought experiment
Identifying subtleties in syntax
In this thought experiment, apply what you've learned about this objective. You can
find answers to these questions in the “Answers” section at the end of this chapter.
Various constructs perform the same function but with a different syntax. For
example, the real difference between a
switch
statement and nested
if…else
state-
ments is minimal. Also, the
while
and
for
loops both evaluate a condition to know
whether the loop should proceed.
1.
When is a
for
loop better than a
while
loop?
2.
How is the readability of the code affected?
■
The
for
and
for…in
iterate for a known length of values.
■
The
while
and
do…while
loops run until a Boolean condition is set to
false
.
■
Arrays provide a mechanism in which to create lists of things.
Search WWH ::
Custom Search