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.
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>');
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);
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();
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.
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;
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("11", 2); // returns 3 (1*2 + 1) parseInt("ff", 16); // returns 255 (15*16 + 15) parseInt("zz", 36); // returns 1295 (35*36 + 35)
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
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"
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(); }