You might be wondering which method is used to convert a JavaScript array into a string. To convert a JS array to a string with commas, we can use the toString()
method to return a comma separated string of the array values.
Every JavaScript object has a 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
Let’s start by defining an array that we will use for these JavaScript examples.
const sports = ["Tennis", "Swimming", "Golf", "Basketball"];
Convert JavaScript array to string with commas
Calling the 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'
Convert JavaScript array to string without commas (with spaces)
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'
Summary
You now know several ways to convert a Javascript array to a string with commas. You will also know how to show it without commas, and how to use a custom separator when you print an array as a string.