23.04.2013 Views

javascript

javascript

javascript

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Figure 4–11. Rummaging through the spices array with a do while loop<br />

CHAPTER 4 ■ CONTROLLING FLOW<br />

Here, === will compare "cinnamon" to "lemon peel" no matter what, since JavaScript always takes at<br />

least one roundabout of a do while loop. Thereafter, JavaScript will do another iteration only if i <<br />

spices.length returns true. Since spices.length evaluates to 15, JavaScript will run the do while path 15<br />

times unless we tell it otherwise with a break statement, which we do in the event we find "lemon peel"<br />

in spices. Finally, our loop variable i contains the index by which we query elements in spices, so we<br />

increment i with the ++ operator at the end of the path. In this way, JavaScript can decide whether there<br />

is any point to taking another roundabout.<br />

In the event that JavaScript finds "lemon peel" while rummaging through spices, it assigns false to<br />

putTheKaiboshOn. This variable in turn enables JavaScript to decide whether our recipe is doable. If<br />

putTheKaiboshOn is false, JavaScript prints "Go right ahead!". Otherwise, it prints "No can do!". Test<br />

that your code works both ways by running the sample with and without "lemon peel" in the spices<br />

array.<br />

Before moving on, let’s rework our do while loop as a while loop. Doing so illustrates that JavaScript<br />

unconditionally takes the first roundabout of a do while loop and then conditionally takes any<br />

subsequent ones. Therefore, to emulate such behavior with a while loop, you would have to key in the<br />

path twice like so:<br />

path<br />

while (expression) path<br />

With this in mind, click Clear in both Firebug panels, and let’s try to pull this off:<br />

var spices = [<br />

"cinnamon",<br />

"ginger",<br />

123

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!