Convert Array to comma separated String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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 will 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 purposes, we used a comma separator.

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

You can pass any value for the separator to the Array.join method. Here are some 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 an 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 Array.join method because it is more explicit and easier to read. Many developers might not be aware that the commas are preserved when you convert an array to a string.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.