Using toString() in JavaScript to convert data types to String

By: Nicholas C. Zakas  

The interesting thing about JavaScript primitive values for Booleans, numbers, and strings is that they are pseudo-objects, meaning that they actually have properties and methods. For example, to get the length of a string, you can do the following:

var sColor = “blue”;

alert(sColor.length); //outputs “4”

Even though the value “blue” is a primitive string, it still has a length property holding the size of the string. To that end, the three main primitive values, Booleans, numbers, and strings, all have a toString() method to convert their value to a string.

You may be asking, “Isn’t it ridiculously redundant to have a toString() method for a string?” Yes, it is. But ECMAScript defines all objects, whether they are pseudo-objects representing primitive values or full-fledged objects, to have a toString() method. Because the string type falls in the category of pseudo-object, it also must have a toString() method.

The Boolean toString() method simply outputs the string “true” or “false”, depending on the value of the variable:

var bFound = false;

alert(bFound.toString()); //outputs “false”

The Number toString() method is unique in that it has two modes: default and radix mode. In default mode, the toString() method simply outputs the numeric value in an appropriate string (whether that is integer, floating point, or e-notation), like this:

var iNum1 = 10;

var fNum2 = 10.0;

alert(iNum1.toString()); //outputs “10”

alert(fNum2.toString()); //outputs “10”

In default mode, the Number’s toString() method always returns the decimal representation of the number, regardless of how you originally specified it. Therefore, numbers specified by octal or hexadecimal literals are output as decimal.

When you use the Number’s toString() method in radix mode, it is possible to output the number using a different base, such as 2 for binary, 8 for octal, or 16 for hexadecimal. The radix is just a fancy name for the base to convert to, and it is specified as an argument to the toString() method:

var iNum = 10;

alert(iNum1.toString(2)); //outputs “1010”

alert(iNum1.toString(8)); //outputs “12”

alert(iNum1.toString(16)); //outputs “A”

In the previous example, the number 10 is output in three different ways: binary, octal, and hexadecimal. This functionality can be very useful for dealing with numbers in HTML, which use hexadecimal representations for each color.

Calling toString(10) on a number is the same as calling toString(); they both return the decimal equivalent of the number.

Archived Comments

Most Viewed Articles (in Javascript )

Latest Articles (in Javascript)

Comment on this tutorial