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'
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.