23.04.2013 Views

javascript

javascript

javascript

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 4 ■ CONTROLLING FLOW<br />

122<br />

Writing a do while loop<br />

while loops provide a way to conditionally run a path zero or more times. That is, if the loop expression<br />

equates to false when it is first evaluated, then the path will not run at all. Now what if you want to make<br />

sure the path runs at least one time? For this circumstance, you would write a do while loop. The syntax<br />

for do while is as follows:<br />

do path while (expression);<br />

As you might guess by now, path can be either a single child statement or a block, and the value of<br />

expression is converted to a boolean if necessary by passing it to Boolean(). Though it is easy to<br />

overlook, the semicolon following the expression in parentheses is required. With those things in mind,<br />

click Clear in both Firebug panels, and let’s try a do while loop.<br />

More often than not, when it comes time to follow a recipe, there is a spice that if unavailable would<br />

put the kaibosh on my plans. Say I want to make lemon scones; the limiting ingredient would be, oddly<br />

enough, lemon peel. Being a foodie, it is safe to assume I have at least one spice. Therefore, it makes<br />

sense to rummage through the spice shelf with a do while loop like so, because we want to check at least<br />

one spice:<br />

var spices = [<br />

"cinnamon",<br />

"ginger",<br />

"nutmeg",<br />

"cloves",<br />

"sesame seed",<br />

"pepper",<br />

"rosemary",<br />

"tarragon",<br />

"basil",<br />

"mace",<br />

"poppy seed",<br />

"lemon peel",<br />

"vanilla",<br />

"oregano",<br />

"allspice",<br />

"thyme"<br />

];<br />

var putTheKaiboshOn = true;<br />

var i = 0;<br />

do {<br />

if (spices[i] === "lemon peel") {<br />

putTheKaiboshOn = false;<br />

break;<br />

}<br />

i ++;<br />

} while (i < spices.length);<br />

(putTheKaiboshOn) ? "No can do!" : "Go right ahead!";<br />

// "Go right ahead!"<br />

Verify your work with Figure 4–11.

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

Saved successfully!

Ooh no, something went wrong!