HTML and CSS Reference
In-Depth Information
This section contains the solutions to the thought experiments and answers to the objective
review questions in this chapter.
Objective 2.1: Thought experiment
Writing clean JavaScript comes with some clear advantages. Choosing the correct construct to
handle a problem is imperative to achieving the goal of clean script.
A
for
loop and
while
loop can both get the same jobs done interchangeably, but some se-
mantic differences make one more preferable over the other in various situations. When you
know how many times a loop must run, the
for
loop is ideal. It has all the built-in semantics
to handle a counter to iterate a known number of times. It can be replaced with a
while
loop,
but the
while
loop requires extra variables and code added to the loop to take care of the
counting of the number of times the loop runs.
The
while
loop is better when you don't know the number of times a loop will run; it's
indeterminate. This is where the loop runs until the logic within the loop achieves a certain
state; hence, why the
while
loop evaluates on a Boolean expression.
You can apply the same logic when choosing between an
if
statement and a
switch
state-
ment. Although a
switch
statement can easily be replaced by an
if
statement, the inverse isn't
true. Checking single values for equality in an
if…else
construct can become long and cum-
bersome.
if
statements allow for more complex evaluations, including compound evaluations
using AND and OR logic. s
witch
statements are more useful for evaluating a single value
against a long list of possible values such as enumeration. Choosing the correct construct for
the problem is imperative to readable and maintainable script.
Objective 2.1: Review
Correct answer:
C
1.
Incorrect:
The
if
statement provides branch flow control.
A.
Incorrect:
The
switch
statement provides branch flow control.
B.
Correct:
The
for
loop provides iterative flow control.
C.
Incorrect:
The
break
keyword is used to exit an iterative control block such as a
for
or
while
loop.
D.
Correct answer:
D
2.
Incorrect:
The
join
method joins all the elements of an array into a string.
A.
Incorrect:
combine
isn't a valid method.
B.
Incorrect:
The
split
method is used to split a string into an array of substrings.
C.
Correct:
The
concat
method combines the elements of two arrays into one array.
D.
Search WWH ::
Custom Search