Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Converting Between Data Types

JavaScript handles conversions between data types for you whenever it can. For example, you've already used statements like this:

document.write("The total is " + total);

This statement prints out a message such as "The total is 40." Since the document.write function works with strings, the JavaScript interpreter automatically converts any non-strings in the expression (in this case, the value of total) to strings before performing the function.

This works equally well with floating-point and boolean values. However, there are some situations where it won't work. For example, the following statement will work fine if the value of total is 40:

average = total / 3;

However, the total variable could also contain a string; in this case, the statement above would result in an error.

In some situations, you may end up with a string containing a number, and need to convert it to a regular numeric variable. JavaScript includes two functions for this purpose:

Both of these functions will read a number from the beginning of the string, and return a numeric version. For example, these statements convert the string "30 angry polar bears" to a number:

stringvar = "30 angry polar bears";
numvar = parseInt(stringvar);

After these statements execute, the numvar variable contains the number 30. The non-numeric portion of the string is ignored.

Share ThisShare This

Informit Network