Chapter 8. Loop Statements
In the
previous chapter, we learned that a conditional
causes a statement block to be executed once if the value of its test
expression is true. A loop,
on the other hand, causes a statement block to be executed
repeatedly, for as long as its test expression remains
true.
Loops come in a variety of tasty flavors: while,
do-while, for, and
for-in. The first three types have very similar
effects, but with varying syntax. The last type of loop,
for-in, is a specialized kind of loop used with
objects. We’ll start our exploration of loops with the
while statement, the easiest kind of loop to
understand.
The while Loop
Structurally, a while
statement is constructed much like an
if statement: a main statement encloses a block
of
substatements that are executed only when a
given condition is true:
while (condition) {substatements}
If the condition is true,
substatements are executed. But unlike the
if statement, when the last substatement is
finished, execution begins anew at the beginning of the
while statement (that is the interpreter
“loops” back to the beginning of the
while statement). The second pass through the
while statement works just like the first: the
condition is evaluated, and if it is still true,
substatements are executed again. This
process continues until condition becomes
false, at which point execution continues with any
statements that follow the while statement in
the script.
Here’s an example of a very simple loop:
var i = 3; while (i < 5) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access