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 />

106<br />

smoothie = "Fage cultured cream";<br />

else if (fridge.lifeway)<br />

smoothie = "Lifeway Greek-style kefir";<br />

else<br />

smoothie = "Dannon yogurt";<br />

smoothie += ", grass-fed cream and milk, Saigon cinnamon, and wild blueberries."<br />

// "Dannon yogurt, grass-fed cream and milk, Saigon cinnamon, and wild blueberries."<br />

Controlling Flow with Conditional Expressions<br />

In the event that your if and else clauses contain single expression statements, you may more elegantly<br />

control flow with a conditional expression using the ?: operator, which we covered in Chapter 3.<br />

Moreover, you may nest conditional expressions to emulate the else if idiom, too.<br />

■ Note Even though you can create an expression statement by simply pinning a semicolon tail to any expression,<br />

you generally do so only for assignment, invocation, increment, or decrement expressions.<br />

Click Clear in both Firebug panels, and rewrite our else if sample using nested conditional<br />

expressions like so:<br />

var fridge = {<br />

brownCow: true,<br />

stonyfield: false,<br />

fage: true,<br />

lifeway: false<br />

};<br />

var smoothie = fridge.brownCow ? "Brown Cow cream-top yogurt" :<br />

(fridge.stonyfield ? "Stonyfield cream-top yogurt" :<br />

(fridge.fage ? "Fage cultured cream" :<br />

(fridge.lifeway ? "Lifeway Greek-style kefir" : "Dannon yogurt")));<br />

smoothie += ", grass-fed cream and milk, Saigon cinnamon, and wild blueberries."<br />

// "Brown Cow cream-top yogurt, grass-fed cream and milk, Saigon cinnamon,<br />

// and wild blueberries."<br />

Verify your work with Figure 4–4.

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

Saved successfully!

Ooh no, something went wrong!