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.

Being weakly typed is both a blessing and a curse for <strong>JavaScript</strong>. While weak typing appears to<br />

free the programmer from having to declare types ahead of time, it does so at the expense of<br />

introducing subtle typing errors. For example, given the following script that manipulates<br />

various string and number values, we will see type conversions cause potential ambiguities:<br />

document.write(4*3);<br />

document.write("");<br />

document.write("5" + 5);<br />

document.write("");<br />

document.write("5" - 3);<br />

document.write("");<br />

document.write(5 * "5");<br />

<strong>The</strong> output of this example when included in an HTML document is shown here:<br />

Notice in most of the examples the string was converted to a number before calculation and the<br />

correct result was produced. Of course, if we would have attempted to do something like "cat" –<br />

3, we would have seen a result of NaN because the string "cat" would convert to NaN and then<br />

the subtraction would produce NaN as well. However, in the case of the addition of "5" + 5, the<br />

answer was actually the string "55" rather than a number 10. <strong>The</strong> reason the addition didn‘t<br />

work is that the plus sign serves two meanings, both as addition and as string concatenation.<br />

Type conversion, coupled with overloaded operators like +, can create all sorts of confusion for<br />

the beginning and advanced programmer alike, so we spend a great deal of time on the subject<br />

in Chapter 3. Fortunately, the rules presented there are relatively logical and there are many<br />

ways to convert data predictably in <strong>JavaScript</strong> using methods like parseFloat() and to even<br />

check the value of a variable using the typeof operator. For example,<br />

var x = "5";<br />

alert (typeof x);<br />

correctly identifies text after x as a string value, as shown here:

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

Saved successfully!

Ooh no, something went wrong!