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.

Number "NaN", "0", or the string representation of<br />

the numeric value<br />

Other object Value of object's toString() method if it<br />

exists, else "undefined"<br />

var x = "false"; // a string<br />

if (x)<br />

{<br />

}<br />

alert("x evaluated to the Boolean value true");<br />

Since every string but the empty string ("") converts to the Boolean value of true, the<br />

conditional is executed and the user is shown the alert.<br />

<strong>The</strong>se type conversion rules mean that comparisons such as<br />

1 == true<br />

0 == ""<br />

are true. But sometimes you don‘t want type conversion to be applied when checking equality,<br />

so <strong>JavaScript</strong> provides the strict equality operator (=). This operator evaluates to true only if its<br />

two operands are equal and they have the same type. So, for example, the following<br />

comparisons would be false:<br />

1 === true<br />

0 === ""<br />

0 === "0"<br />

How the <strong>JavaScript</strong> interpreter determines the type required for most operators is fairly natural<br />

and isn‘t required knowledge for most developers. For example, when performing arithmetic,<br />

types are converted into numbers, then computations are performed.<br />

One important exception is the + operator. <strong>The</strong> + operator performs addition on numbers but<br />

also serves as the concatenation operator for strings. Because string concatenation has<br />

precedence over numeric addition, + will be interpreted as string concatenation if any of the<br />

operands are strings. For example, both statements,<br />

x = "2" + "3";<br />

x = "2" + 3;<br />

result in the assignment of the string "23" to x. <strong>The</strong> numeric 3 in the second statement is<br />

automatically converted to a string before concatenation is applied.<br />

Promotion of Primitive Data to Objects<br />

It was previously mentioned that there is an object corresponding to each primitive type. <strong>The</strong>se<br />

objects provide useful methods for manipulating primitive data. For example, the String object<br />

provides a method to convert a string to lowercase: toLowerCase(). You can invoke this<br />

method on a String object:

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

Saved successfully!

Ooh no, something went wrong!