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.

CHAPTER 3 ■ OPERATORS<br />

66<br />

Figure 3–5. JavaScript converts NaN to a wrapper object if you query it with the . or [] operator.<br />

Finally, it’s vital to remember that the left operand to +=, -=, *=, or /= must be a variable, member,<br />

element, or parameter. Otherwise, JavaScript will slap you upside the head by returning a SyntaxError<br />

noting, "invalid assignment left-hand side", which means the left operand must be one of these<br />

things.<br />

3 -= 1;<br />

// SyntaxError: invalid assignment left-hand side { message="invalid assignment left-hand<br />

side" }<br />

"blue" += "berries";<br />

// SyntaxError: invalid assignment left-hand side { message="invalid assignment left-hand<br />

side" }<br />

Incrementing or Decrementing Values<br />

In the event that you are adding or subtracting 1 from a value with += or -=, you may even more<br />

succinctly do so with the ++ increment and -- decrement unary operators, which convert it to a number<br />

if necessary. Note that although += may do addition or concatenation, ++ always does addition.<br />

So in Firebug, let’s double saigonCinnamon with ++ and halve mincedLemonZest with --, verifying our<br />

work with Figure 3–6.<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 />

};<br />

dough.saigonCinnamon[0] ++;<br />

dough.mincedLemonZest[0] --;

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

Saved successfully!

Ooh no, something went wrong!