2
Newlines after
return
statements will cause problems; see
for more information.
funds
=
funds
-
1
;
// one step back
}
This
while
loop will eventually terminate: every time through the loop,
funds
increa‐
ses by two and decreases by one for a net of 1. Eventually,
funds
will be 100 and the
loop will terminate.
While it’s very common to use a block statement with control flow, it’s not required.
For example, if we wanted to simply count up to 100 by twos, we don’t need a block
statement:
let
funds
=
50
;
// starting conditions
while
(
funds
>
1
&&
funds
<
100
)
funds
=
funds
+
2
;
Whitespace
For the most part, JavaScript doesn’t care about additional whitespace (including
newlines
): 1 space is as good as 10, or 10 spaces and 10 newlines. This doesn’t mean
you should use whitespace capriciously. For example, the preceding
while
statement
is equivalent to:
while
(
funds
>
1
&&
funds
<
100
)
funds
=
funds
+
2
;
But this hardly makes it look as if the two statements are connected! Using this for‐
matting is very misleading, and should be avoided. The following equivalents, how‐
ever, are relatively common, and mostly unambiguous:
// no newline
while
(
funds
>
1
&&
funds
<
100
)
funds
=
funds
+
2
;
// no newline, block with one statement
while
(
funds
>
1
&&
funds
<
100
) {
funds
=
funds
+
2
; }
There are those who insist that control flow statement bodies—for the sake of consis‐
tency and clarity—should always be a block statement (even if they contain only one
statement). While I do not fall in this camp, I should point out that careless indenta‐
tion fuels the fire of this argument:
while
(
funds
>
1
&&
funds
<
100
)
funds
=
funds
+
2
;
funds
=
funds
-
1
;
60 | Chapter 4: Control Flow