11.12.2012 Views

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

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.

<strong>The</strong>re is one further wrinkle with the + operator. Because addition and concatenation in an<br />

expression are evaluated by the interpreter from left to right, any leading occurrences of + with<br />

two numeric operands (or types that can be automatically converted to numbers) will be treated<br />

as addition. For example,<br />

var w = 5;<br />

var x = 10;<br />

var y = "I am string ";<br />

var z = true;<br />

alert(w+x+y+z);<br />

displays the following dialog:<br />

<strong>The</strong> addition of w and x happens before the string concatenation occurs. However, you could<br />

force a different order of evaluation with the appropriate application of parentheses. See the<br />

section ―Operator Precedence and Associativity‖ later in this chapter for more information.<br />

One trick often used to force + to function as string concatenation is to use the empty string at<br />

the beginning of the expression. For example:<br />

var w = 5;<br />

var x = 10;<br />

var y = "I am string ";<br />

var z = true;<br />

alert(""+w+x+y+z);<br />

<strong>The</strong> result is<br />

To force + to operate as addition, you need to use an explicit type conversion function as<br />

discussed in Chapter 7.

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

Saved successfully!

Ooh no, something went wrong!