Javascript Array toString()

The JavaScript Array toString() method returns a string representing the specified array and its elements.

The syntax of the toString() method is:

arr.toString()

Here, arr is an array.


toString() Parameters

The toString() method does not have any parameters.


Return value from toString()

  • Returns a String, representing the values of the array separated by a comma

Notes:

  • The toString() method does not change the original array.
  • Elements like undefined, null, or empty array, have an empty string representation.

Example: Using toString() method

var info = ["Terence", 28, "Kathmandu"];

var info_str = info.toString();

// toString() does not change the original array
console.log(info); // [ 'Terence', 28, 'Kathmandu' ]

// toString() returns the string representation
console.log(info_str); // Terence,28,Kathmandu

var collection = [5, null, 10, "JavaScript", NaN, [3, [14, 15]]];
console.log(collection.toString()); // 5,,10,JavaScript,NaN,3,14,15

Output

[ 'Terence', 28, 'Kathmandu' ]
Terence,28,Kathmandu
5,,10,JavaScript,NaN,3,14,15

Here, we can see that the toString() method converts all the array elements into a string and separates each element by a comma.


Recommended Readings: