Borislav Hadzhiev
Wed Oct 20 2021·2 min read
Photo by Lucas Defibaugh
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.
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.
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.
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.
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.
const arr = ['one', 'two', null]; console.log(String(arr)); // 👉️ one,two, console.log(arr.join(',')); // 👉️ one,two,
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.