You can convert an array to a comma separated string in JavaScript by calling the Array.prototype.toString()
method on the array, for example, like so:
const arr = ['foo', 'bar', 'baz']; console.log(arr.toString()); // 'foo,bar,baz'
You can also use the Array.prototype.join()
method to achieve the same:
const arr = ['foo', 'bar', 'baz']; console.log(arr.join()); // 'foo,bar,baz'
In fact, under the hood, the Array.prototype.toString()
method calls Array.prototype.join()
to convert an array into a comma separated string. One difference between the two methods is that, Array.prototype.join()
also allows you to specify a custom separator string:
const arr = ['foo', 'bar', 'baz']; console.log(arr.join(', ')); // 'foo, bar, baz'
Hope you found this post useful. It was published . Please show your love and support by sharing this post.