You can convert an array to a comma separated string in JavaScript using any of the following methods –
- Use the Array.join() method passing comma (,) as an argument. This will convert the array to a comma separated string.
- Use String(array) which will convert the array to a comma separated string.
Let’s discuss each of these methods in detail below.
Convert An Array To A Comma Separated String In JavaScript
Use The Array.join() Method Passing Comma (,) As An Argument
The Array.join() method is used to join all the elements of an array into a string. This method accepts an optional argument which is a separator used to join the array elements. If no separator is provided, a comma (,) is used by default.
Consider the following example –
var arr = [‘Hello’, ‘World’];
console.log(arr.join()); // Hello,World
console.log(arr.join(‘ ‘)); // Hello World
console.log(arr.join(‘+’)); // Hello+World
As you can see from the above example, if no separator is provided, a comma is used as the default separator. But, you can also pass in a custom separator of your choice.
If you call the join() method on an empty array, it will return an empty string.
Example
var arr = [];
console.log(arr.join()); // ""
If you call the join() method on an array of which any one of the elements is null or undefined, the null or undefined element will be converted to an empty string.
Example
var arr = [‘Hello’, undefined, ‘World’];
console.log(arr.join()); // Hello,,World"
Use String(array) To Convert Array To Comma Separated String
You can convert an array to a string using the String(array) function. This function converts the elements of an array to strings and then joins them together with a comma separator.
Consider the following example –
var arr = [‘Hello’, ‘World’];
console.log(String(arr)); // Hello,World
As you can see from the above example, when you convert an array to a string using the String(array) function, it joins the array elements with a comma (,) separator.
If you try to convert an empty array to a string using the String(array) function, it will return an empty string.
Example
var arr = [];
console.log(String(arr)); // ""
If you try to convert an array consisting of any one of the elements is null or undefined, the null or undefined element will be converted to an empty string.
Example
var arr = [‘Hello’, undefined, ‘World’];
console.log(String(arr)); // "Hello,,World"
As you can see, there are two ways to convert an array to a comma separated string in JavaScript – using the Array.join() method and using the String(array) function. Which method you choose to use depends on your personal preference. Personally, I use Array.join() method as it’s more concise and reads better.
I hope this article was helpful. Thank you for reading! 🙂