Javascript Array toString()

The toString() method returns a string formed by the elements of the given array.

Example

// defining an array
let items = ["JavaScript", 1, "a", 3];

// returns a string with elements of the array separated by commas let itemsString = items.toString();
console.log(itemsString); // Output: // JavaScript,1,a,3

toString() Syntax

The syntax of the toString() method is:

arr.toString()

Here, arr is an array.


toString() Parameters

The toString() method does not take any parameters.


toString() Return Value

  • 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 1: Using toString() Method

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

// returns the string representation of the info array let info_str = info.toString();
console.log(info_str); // toString() does not change the original array console.log(info);

Output

Terence,28,Kathmandu
[ 'Terence', 28, 'Kathmandu' ]

In the above example, we have used the toString() method to convert all the elements of the info array into a string.

info.toString() returns the string representation of info which is Terence,28,Kathmandu.

Since the method does not change the original array, the info array holds the same original value.


Example 2: toString() with Nested Arrays

When we use the toString() method in a nested array, the array is flattened. For example:

// defining a nested array
let nestedArray = [1, 2, 4, ["Apple", 5]];

// returns string representation of the nested array by flattening the array let resultingArray = nestedArray.toString();
console.log(resultingArray);

Output

1,2,4,Apple,5

Also Read:

Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community