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 3 ■ OPERATORS<br />

64<br />

mincedLemonZest: [2, "tsp"],<br />

seaSalt: [1/4, "tsp"],<br />

soda: [1, "tsp"],<br />

tartar: [1, "tsp"],<br />

pourableVanillaYogurt: [1, "cup"],<br />

egg: [1],<br />

wildBlueberries: [1 + 1/4, "cup"]<br />

};<br />

dough.pourableVanillaYogurt[0] += "1";<br />

dough.pourableVanillaYogurt[0];<br />

// "11"<br />

Figure 3–3. += only does concatenation if its right operand is not a number.<br />

Remember that every JavaScript value can be converted to a boolean or string, but not to a number.<br />

Not one you can do math with anyway. Most non-numbers convert to the “not a number” literal NaN.<br />

Moreover, the return value of any math operation containing a NaN operand will always be NaN.<br />

Insofar as JavaScript returns NaN whenever a value cannot be converted to a number, +=, -=, *=, and<br />

/= may overwrite a variable, member, element, or parameter with NaN. To illustrate the point, try the<br />

following sample, verifying your work with Figure 3–4. Insofar as we forgot to refine our query with the<br />

[] operator, JavaScript multiplies the array [1 + 1/4, “cup”] by 3. Therefore, [1 + 1/4, “cup”] is converted<br />

to the number NaN and multiplied by 3. So, the array in dough.wildBlueberries is overwritten with the<br />

return value of NaN * 3, which of course is NaN.<br />

var dough = {<br />

pastryFlour: [1 + 3/4, "cup"],<br />

almondFlour: [1/3, "cup"],<br />

saigonCinnamon: [1, "tsp"],<br />

mincedLemonZest: [2, "tsp"],<br />

seaSalt: [1/4, "tsp"],<br />

soda: [1, "tsp"],<br />

tartar: [1, "tsp"],<br />

pourableVanillaYogurt: [1, "cup"],<br />

egg: [1],<br />

wildBlueberries: [1 + 1/4, "cup"]<br />

};

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

Saved successfully!

Ooh no, something went wrong!