while Loops
We finally have something that we can translate directly into code. Our flowchart
already has the first control flow statement we’ll be discussing, a
while
loop. A
while
loop repeats code as long as its condition is met. In our flowchart, the condition is
funds > 1 && funds < 100
. Let’s see how that looks in code:
let
funds
=
50
;
// starting conditions
while
(
funds
>
1
&&
funds
<
100
) {
// place bets
// roll dice
// collect winnings
}
If we run this program as is, it will run forever, because funds start at 50 pence, and
they never increase or decrease, so the condition is always true. Before we start filling
out details, though, we need to talk about block statements.
Block Statements
Block statements (sometimes called compound statements) are not control flow state‐
ments, but they go hand in hand with them. A block statement is just a series of state‐
ments enclosed in curly braces that is treated by JavaScript as a single unit. While it is
possible to have a block statement by itself, it has little utility. For example:
{
// start block statement
console
.
log
(
"statement 1"
);
console
.
log
(
"statement 2"
);
}
// end block statement
console
.
log
(
"statement 3"
);
The first two calls to
console.log
are inside a block; this is a meaningless but valid
example.
Where block statements become useful is with control flow statements. For example,
the loop we’re executing with our
while
statement will execute the entire block state‐
ment before testing the condition again. For example, if we wanted to take “two steps
forward and one step back,” we could write:
let
funds
=
50
;
// starting conditions
while
(
funds
>
1
&&
funds
<
100
) {
funds
=
funds
+
2
;
// two steps forward
A Control Flow Primer | 59