home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


JavaScript: The Definitive Guide

Previous Chapter 9
Further Topics in JavaScript
Next
 

9.2 Explicit Data Type Conversions

The section above described all of the automatic data type conversions performed by JavaScript. Sometimes, however, you will want to explicitly convert a value from one type to another. For example, instead of repeatedly using a number in a string context, and relying on JavaScript to convert it to a string, you might prefer (for efficiency) to convert the number to a string a single time and then repeatedly use the converted value. Or, you might simply prefer to make your data type conversions explicit so that your code is easier to understand.

JavaScript does not have a cast operator, a mechanism often used in C, C++, and Java to convert values from one type to another. To force a conversion in JavaScript, you must generally invoke a function or method. The sections below show how you can do this.

Conversions to and from Objects

We saw in the section on automatic conversions that all objects have a toString() method that provides at least a default string conversion for each object type. Similarly, many objects define a valueOf() method that returns the primitive type equivalent of the object. Although these methods are invoked automatically under certain appropriate circumstances, there is nothing to prevent you from using them explicitly to convert objects. For example, you might use lines of code like the following to perform explicit conversions of Date objects:

message = "Today is: " + today.toString();
elapsed_time = end_time.valueOf() - start_time.valueOf();

Also remember that primitive types are automatically converted to objects when used in an object context, so you can invoke the toString() method on a primitive type to explicitly convert it to a string. For example:

// define one of our functions in a new document in a new window
newwin.document.write('<script>' + myfunc.toString() + '</' + 'script>');
Note that because of syntactic constraints in JavaScript, you can't directly invoke the toString() method on a numeric literal (although you can on string and Boolean literals). You must enclose the number in parentheses, or must first assign it to a variable:

321.toString();          // this is a syntax error
(123).toString();        // this is okay
a = 45; a.toString();    // also okay
true.toString();         // this works fine

Although you may less frequently need to do it, you can also explicitly convert primitive values to their corresponding String, Number, Boolean, and Function object values. You can use the constructor methods for each of these object types, or you can simply use the Object() constructor instead:

func_obj = new Object(my_func);    // these two lines are equivalent
func_obj = new Function(my_func);

Converting Numbers to Strings

The number-to-string conversion is probably the one most often performed in JavaScript. Although it usually happens automatically, there are a couple of useful ways to perform this conversion explicitly. Perhaps the simplest is to add the empty string to a number. This forces the number to be converted (because it is used in a string context) and concatenated with nothing:

string_value = number + "";

Another technique for converting numbers to strings is with the toString() method, as we saw above:

string_value = number.toString();
The toString() method of the Number object (numbers are converted to Number objects so that this method can be called) takes an optional argument that specifies a radix, or base, for the conversion. If you do not specify the argument, the conversion will be done in base 10. But you can also convert numbers in other bases (between 2 and 16) as well. For example:

binary_string = n.toString(2);
octal_string = "0" + n.toString(8);
hex_string = "0x" + n.toString(16);

A shortcoming of JavaScript is that there is no built-in way to convert a number to a string and specify the number of decimal places to be included. This can make it a little difficult to display numbers that represent monetary values, and which have a traditional format. In fact, JavaScript lacks any kind of numeric formatting function, so it is not possible to specify whether exponential notation should be used or not, nor whether leading zeros should be displayed, and so on.

Converting Strings to Numbers

We've seen that strings that represent numbers are automatically converted to actual numbers when used in a numeric context. We can make this conversion explicit by choosing the numeric context we use. Just as we can convert a number to a string by adding the empty string to it, we can convert a string to a number by subtracting zero from it:

numeric_value = string_value - 0;
We can't add zero, of course, because in that case the + operator would be interpreted as the string concatenation operator.

The trouble with this sort of string-to-number conversion is that it is overly strict. It works only with base-10 numbers, and only when the string contains nothing but leading spaces and numbers, with no trailing characters, not even trailing spaces. To allow more flexible conversions, you can use the parseInt() and parseFloat() functions. These convert and return any number at the beginning of a string, ignoring any trailing non-numbers. parseInt() only parses integers, and parseFloat() parses both integers and floating-point numbers. If a number begins with 0, parseInt() interprets it as an octal number. If it begins with 0x or 0X, parseInt() interprets it as a hexadecimal number.

parseInt("3 blind mice");      // returns 3
parseFloat("3.14 meters");     // returns 3.14
parseInt("12.34");             // returns 12
parseInt("077");               // returns 63 (7*8 + 7)
parseInt("0xFF");              // returns 255
parseInt() can even take a second argument, which specifies the radix (base) of the number to be parsed. Legal values are between 2 and 36. For example:

parseInt("11", 2);             // returns 3 (1*2 + 1)
parseInt("ff", 16);            // returns 255 (15*16 + 15)
parseInt("zz", 36);            // returns 1295 (35*36 + 35)
If parseInt() or parseFloat() cannot convert the specified string to a number, they return NaN in Navigator 3.0 (and on Unix platforms in Navigator 2.0). On Navigator 2.0 non-Unix platforms and in Internet Explorer 3.0, these functions return 0 in this case, which makes it impossible to distinguish between the legal string "0" and an a string that does not represent a number. A future version of IE will correctly support the NaN return value.

parseInt("eleven");            // returns NaN (or 0)
parseFloat("$72.47");          // returns NaN (or 0)

Finally, you can also convert strings to numbers (and to other types) with the eval() method. This method interprets an arbitrary JavaScript expression and returns the result (which may be of any JavaScript type). For example:

eval("3.14");                  // returns 3.14
eval("2 * 3.14 * radius");     // returns the result of the multiplication
eval("radius > 3");            // returns true or false
Note that you rarely actually need to use eval()--generally, your JavaScript expressions occur in JavaScript code itself, not in strings that are later evaluated!

Miscellaneous Conversions

JavaScript does not contain any built-in conversion functions other than those described above. You can write your own JavaScript code to perform certain conversions for you, however. To explicitly convert between boolean values and numeric values, for example, you could use expressions like the following:

b?1:0              // converts a boolean, b, to a number
(x==0)?false:true  // converts a number, x, to a boolean

You may write your own code for custom data conversions. For example, to convert a boolean value to either the string "yes" or "no", you might use:

(reply)?"yes":"no"
To convert an arbitrary value to a string, you might write a function like the following, which follows some custom rules:

function convert_to_string(x)
{
    if (x == null) return "";
    if (typeof x == "boolean") return x?"on":"off";
    if (typeof x == "function") return "[function]";
    return x.toString();
}


Previous Home Next
Automatic Data Type Conversion Book Index By Value vs. By Reference

HTML: The Definitive Guide CGI Programming JavaScript: The Definitive Guide Programming Perl WebMaster in a Nutshell