Convert Array to comma separated String in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

Convert Array to comma-separated String #

To convert an array to a comma-separated string, pass the array as a parameter to the String object - String(arr). The String object will convert the passed in array to a comma-separated string and return the result.

index.js
const arr = ['one', 'two', 'three']; const str = String(arr); console.log(str); // ๐Ÿ‘‰๏ธ 'one,two,three' console.log(typeof str); // ๐Ÿ‘‰๏ธ string

The only parameter we passed to the String object is the value we want to convert to a string.

Since we provided an array, the result is a comma-separated string.

An alternative, but also very common approach is to use the Array.join method.

To convert an array to a comma-separated string, call the join() method on the array, passing it a string containing a comma as a parameter. The join method returns a string containing all array elements joined by the provided separator.

index.js
const arr = ['one', 'two', 'three']; const str = arr.join(','); console.log(str); // ๐Ÿ‘‰๏ธ 'one,two,three' console.log(typeof str); // ๐Ÿ‘‰๏ธ string

The only parameter the Array.join method takes is a separator. For our use case, we provide a comma as the separator.

The method returns a string containing all array elements joined by the provided separator.

You can pass any value as the separator to the Array.join method, here are other examples.

index.js
const arr = ['one', 'two', 'three']; const withSpaces = arr.join(' '); console.log(withSpaces); // ๐Ÿ‘‰๏ธ 'one two three' const withCommaAndSpace = arr.join(', '); console.log(withCommaAndSpace); // ๐Ÿ‘‰๏ธ one, two, three const withDashes = arr.join('-'); console.log(withDashes); // ๐Ÿ‘‰๏ธ 'one-two-three' const withoutSeparator = arr.join(''); console.log(withoutSeparator); // ๐Ÿ‘‰๏ธ onetwothree

If you call the join method on an empty array, it returns an empty string.

index.js
console.log([].join(',')); // ๐Ÿ‘‰๏ธ ''

An important thing to note is that if the array contains elements that are undefined, null or empty array [], they get converted to an empty string.

index.js
const arr = ['one', 'two', null]; console.log(String(arr)); // ๐Ÿ‘‰๏ธ one,two, console.log(arr.join(',')); // ๐Ÿ‘‰๏ธ one,two,
My preferred approach is to use the join method, because it is more explicit and easier to read. Many developers might not be aware that when you cast an array to a string, the commas are preserved.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee