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> typeof Operator<br />

If you‘re curious about the type of data you have, use the typeof operator to examine it. Applied<br />

to a variable or literal, it returns a string indicating the type of its argument. <strong>The</strong> list of values<br />

returned by typeof is given in Table 3-4.<br />

Table 3-4: Values Returned by the typeof Operator<br />

Type Result<br />

Undefined undefined<br />

Null object<br />

Boolean boolean<br />

Number number<br />

String string<br />

Object object<br />

Function function<br />

Type Conversion<br />

Automatic type conversion is one of the most powerful features of <strong>JavaScript</strong>, as well as the<br />

most dangerous for the sloppy programmer. Type conversion is the act of converting data of<br />

one type into a different type. It occurs automatically in <strong>JavaScript</strong> when you change the type of<br />

data stored in a variable:<br />

var x = "3.14";<br />

x = 3.14;<br />

<strong>The</strong> type of x changes from string to number. Besides the automatic conversion inherent in<br />

<strong>JavaScript</strong>, it is also possible for programmers to force the conversion using methods like<br />

toString() or parseInt().<br />

While it seems straightforward enough, the problem with type conversion also is that it often<br />

occurs in less obvious ways, such as when you operate on data with dissimilar types. Consider<br />

this code:<br />

var x = "10" - 2;<br />

This example subtracts a number from a string, which should seem very odd at first glance. Yet<br />

<strong>JavaScript</strong> knows that subtraction requires two numbers, so it converts the string "10" into the<br />

number 10, performs the subtraction, and stores the number 8 in x.<br />

<strong>The</strong> truth is that automatic type conversion happens all over the place in <strong>JavaScript</strong>, any time<br />

data is not of the type that might be required for some task. For example, we previously stated<br />

that the type of the condition (the part between the parentheses) of flow control statements like<br />

if/else is Boolean. This means that given a statement like this,<br />

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

if (x)<br />

{

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

Saved successfully!

Ooh no, something went wrong!