toString() method to return a comma separated string of the array values.
toString() method, which is used to show an object only represented by a text string. As always, there is more than one way to show a JS array as strings, separating the values using a space, a comma, or a custom separator.
I’ll include examples of the
array.Join() method too.
Set up a JS array
const sports = ["Tennis", "Swimming", "Golf", "Basketball"];
toString() method on the array will return a string of each array item separated by commas, as shown in this example :
const sports = ['Tennis', 'Swimming', 'Golf', 'Basketball']; var myVar = sports.toString()); // 'Tennis,Swimming,Golf,Basketball'
However there is another way of showing an array as a list of comma separated strings using the
array.Join method, and this method also accepts an optional
separator as an argument. If you don’t specify one it defaults to a comma
var str1 = array.join(); // 'Tennis,Swimming,Golf,Basketball' var str2 = array.join(', '); // 'Tennis, Swimming, Golf, Basketball'
As stated above the
array.join() method accepts a value as a separator. In the example above you can see the string separated with commas or spaces. But because you can specify a custom character as the separator there are other ways you can output this string :
var str3 = array.join(' + '); // 'Tennis + Swimming + Golf + Basketball' var str4 = array.join(''); // 'TennisSwimmingGolfBasketball'