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

So tally < 100 returns false, and JavaScript goes down the else path. Therefore,<br />

mayfly.kmLeftToLive() returns "Mayfly is dead!" to indicate that it’s time to buy a new Mayfly.<br />

By the way, even if you are not a runner, you might want to try the Mayfly sometime. The upper part<br />

is bright orange with a black support grid resembling the wing of a fly—you will be hard to miss in a pair<br />

of those!<br />

To Wrap or Not to Wrap<br />

As noted earlier, whenever a compound statement contains a single child statement, you do not have to<br />

wrap it in curly braces. So, we could have defined mayfly like so, where the bold code shows the single<br />

child statements do not have curly braces:<br />

var mayfly = function () {<br />

var tally = 0;<br />

return {<br />

addToTally: function (km) {<br />

if (typeof km === "number" && isFinite(km))<br />

return tally += km;<br />

else<br />

return "Invalid parameter!";<br />

},<br />

kmLeftToLive: function () {<br />

if (tally < 100)<br />

return "Mayfly has " + (100 - tally) + " kilometers left to live.";<br />

else<br />

return "Mayfly is dead!";<br />

}<br />

}<br />

}();<br />

Furthermore, we could have omitted the line breaks, too:<br />

var mayfly = function () {<br />

var tally = 0;<br />

return {<br />

addToTally: function (km) {<br />

if (typeof km === "number" && isFinite(km)) return tally += km;<br />

else return "Invalid parameter!";<br />

},<br />

kmLeftToLive: function () {<br />

if (tally < 100) return "Mayfly has " + (100 - tally) + " kilometers left to live.";<br />

else return "Mayfly is dead!";<br />

}<br />

}<br />

}();<br />

The else if idiom, which we will cover next, takes advantage of this single-line, no-bracket<br />

JavaScript feature. Moreover, you will encounter both styles in scripts written by others, myself included.<br />

However, as a beginner, you may want to wrap single child statements in curly braces inasmuch as this<br />

eliminates the need for you to remember that two or more child statements need to be wrapped in curly<br />

braces and that an else clause goes with the nearest if condition.<br />

101

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

Saved successfully!

Ooh no, something went wrong!