JavaScript toString() Method
This tutorial covers the JavaScript toString() method. Available to all JavaScript objects, the toString() method returns a string representation of its argument. This tutorial focuses on toString() applied to JavaScript arrays.
To join JavaScript array elements as a string without comma separators, use the join() method.
The toString()
method is not exclusive to JavaScript's Array object: it is inherited from the "Object" object, and all data types (and custom objects) inherit the methods and properties of the Object object.
This tutorial covers toString() as the method specifically applies to JavaScript's Array objects.
Using the toString() Method with JavaScript Arrays
The toString() method returns a string representation of the JavaScript object on which it is called. Applied on an array, toString() will return a string containing all elements in the array, each separated by a comma (","). The script below declares an array, and returns its string representation to an alert box.
var arlene = new Array("I", "learn", "JavaScript");
alert( arlene.toString() );
Your web browser's JavaScript interpreter will usually perform an automatic conversion to string for arguments passed to the alert() method. But you should always use toString() to return a string representation of an object, rather than rely on browser behaviors. The original object is not affected by toString().
The script above returns this result:
Note that calling the toString() method on an array has the exact same effect as calling the join() method with a comma passed as argument.
var arlene = new Array("I", "learn", "JavaScript");
// Both lines below return the same string
alert( arlene.toString() );
alert( arlene.join(",") );
Test the toString() Method
Interactively test the toString() method by editing the JavaScript code below and clicking the Test toString() Method button.
Browser support for JavaScript aScript toString() method | |||
---|---|---|---|