Chaining if...else Statements
Chaining
if...else
statements is not actually a special syntax: it’s simply a series of
if...else
statements where each
else
clause contains another
if...else
. It’s a com‐
mon enough pattern that it deserves mention. For example, if Thomas’s superstition
extends to days of the week, and he’ll only bet a single penny on a Wednesday, we
could combine this logic in an
if...else
chain:
if
(
new
Date
().
getDay
()
===
3
) {
// new Date().getDay() returns the current
totalBet
=
1
;
// numeric day of the week, with 0 = Sunday
}
else
if
(
funds
===
7
) {
totalBet
=
funds
;
}
else
{
console
.
log
(
"No superstition here!"
);
}
By combining
if...else
statements this way, we’ve created a three-way choice,
instead of simply a two-way choice. The astute reader may note that we’re technically
breaking the guideline we established (of not mixing single statements and block
statements), but this is an exception to the rule: it is a common pattern, and is not
confusing to read. We could rewrite this using block statements:
if
(
new
Date
().
getDay
()
===
3
) {
totalBet
=
1
;
}
else
{
if
(
funds
===
7
) {
totalBet
=
funds
;
}
else
{
console
.
log
(
"No superstition here!"
);
}
}
We haven’t really gained any clarity, and we’ve made our code more verbose.
Metasyntax
The term metasyntax means a syntax that, in turn, describes or communicates yet
another syntax. Those with a computer science background will immediately think of
“Extended Backus-Naur Form” (EBNF), which is an incredibly intimidating name for
a simple concept.
For the rest of this chapter, I’ll be using a metasyntax to concisely describe JavaScript
flow control syntax. The metasyntax I’m using is simple and informal and—most
importantly—used for JavaScript documentation on the
. Because the MDN is a resource you will undoubtedly find yourself using
quite often, familiarity with it will be useful.
There are only two real elements to this metasyntax: something surrounded by square
brackets is optional, and an ellipsis (three periods, technically) indicates “more goes
Control Flow Statements in JavaScript | 69