break
;
}
Note that the same action is being taken when the bet is 11 or 13. This is where we
might want to take advantage of fall-through execution. Remember that we said the
switch
statement will keep executing statements until it sees a
break
statement. Using
this to our advantage is called fall-through execution:
switch
(
totalBet
) {
case
7
:
totalBet
=
funds
;
break
;
case
11
:
case
13
:
totalBet
=
0
;
break
;
case
21
:
totalBet
=
21
;
break
;
}
This is pretty straightforward so far: it’s clear that Thomas won’t bet anything if he
happens to pull out 11 or 13 pence. But what if 13 is a far more ominous omen than
11, and requires not only forgoing the bet, but giving a penny to charity? With some
clever rearranging, we can handle this:
switch
(
totalBet
) {
case
7
:
totalBet
=
funds
;
break
;
case
13
:
funds
=
funds
-
1
;
// give 1 pence to charity!
case
11
:
totalBet
=
0
;
break
;
case
21
:
totalBet
=
21
;
break
;
}
If
totalBet
is 13, we give a penny to charity, but because there’s no
break
statement,
we fall through to the next case (11), and additionally set
totalBet
to 0. This code is
valid JavaScript, and furthermore, it is correct: it does what we intended it to do.
However, it does have a weakness: it looks like a mistake (even though it’s correct).
Imagine if a colleague saw this code and thought “Ah, there’s supposed to be a
break
statement there.” They would add the
break
statement, and the code would no longer
be correct. Many people feel that fall-through execution is more trouble than it’s
worth, but if you choose to utilize this feature, I recommend always including a com‐
ment to make it clear that your use of it is intentional.
Control Flow Statements in JavaScript | 73