Main Page

Converting to a string

Converting to a string
The interesting thing about ECMAScript 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
is a primitive string, it still has a
property holding the size of
the string. To that end, the three main primitive values, Booleans, numbers, and strings, all have a
method to convert their value to a string.
You may be asking, “Isn’t it ridiculously redundant to have a
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
method. Because the string type falls in the category of
pseudo-object, it also must have a
The Boolean
method simply outputs the string
, depending on the
value of the variable:
var bFound = false;
alert(bFound.toString()); //outputs “false”
The Number
method is unique in that it has two modes: default and radix mode. In default
mode, the
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
method always returns the decimal representation of the
number, regardless of how you originally specified it. Therefore, numbers specified by octal or hexadeci-
mal literals are output as decimal.
When you use the Number ’s
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
is just a fancy
name for the base to convert to, and it is specified as an argument to the
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 repre-
sentations for each color.
Chapter 2
05_579088 ch02.qxd 3/28/05 11:35 AM Page 22

JavaScript EditorFree JavaScript Editor     Ajax Editor