JavaScript tutorial:
toString method

 

Applies to: Array Object, Boolean Object, Function Object, Number Object, Object Object, String Object

The toString method is use to get a string representation of an object.

Syntax

objectname.toString([radix])

The toString method syntax has these parts:

Part

Description

objectname

Required. An object for which a string representation is sought.

radix

Optional. Specifies a radix for converting numeric values to strings.

Return String

Returns a string representation of an object.

Example

The toString method is a member of all built-in JavaScript objects. How it behaves depends on the object type:

Object

Behavior

Array

Elements of an Array are converted to strings. The resulting strings are concatenated, separated by commas.

Boolean

If the Boolean value is true, returns "true". Otherwise, returns "false"

Function

Returns a string returned of the following form, where functionname is the name of the function whose toString method was called:

function functionname( ) { [native code] }

Number

Returns the textual representation of the number.

String

Returns the value of the String object.

Default

Returns "[object objectname]", where objectname is the name of the object type.

The following example illustrates the use of the toString method with a radix argument:

<HTML>
<HEAD>
<SCRIPT LANGUAGE= JavaScript>
function CreateRadixTable ()
{
var s1, s2, s3, x;
document.write("Hex Dec Bin<BR>");
for (x = 0; x < 16; x++)
{
switch(x)
{
case 0 :
s1 = " ";
s2 = " ";
s3 = " ";
break;
case 1 :
s1 = " ";
s2 = " ";
s3 = " ";
break;
case 2 :
s3 = " ";
break;
case 3 :
s3 = " ";
break;
case 4 :
s3 = " ";
break;
case 5 :
s3 = " ";
break;
case 6 :
s3 = " ";
break;
case 7 :
s3 = " ";
break;
case 8 :
s3 = "" ;
break;
case 9 :
s3 = "";
break;
default:
s1 = " ";
s2 = "";
s3 = " ";
break;
}
document.write(" ", x.toString(16), s1, x.toString(10), s2, s3, x.toString(2), "</br>");
}
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=JavaScript>
CreateRadixTable ();
</SCRIPT>
</BODY>
</HTML>

  To run the code above, paste it into JavaScript Editor, and go to View, Internal Page Viewer or press F5.

See also: function Statement