How to Convert an Array into a Comma Separated String in JavaScript?

To convert an array into a comma separated string in JavaScript you can use the Array.join() method. The Array.join() method joins the array elements with a given separator string and returns a new string containing all array elements joined with the separator string.

So, to convert the array into a comma separated string, you have to simply pass a string containing a comma to the join() method as a parameter and it will return you a comma separated string.

See the following example:

const arr = ['one', 'two', 'three', 'four'];

const str = arr.join(', ');

console.log(str);
// Output: 'one, two, three, four'

console.log(typeof str);
// Output: string

If you do not pass any parameter to the join() method, then also it will convert the array into a comma separated string. But there will be no spaces after the commas.

See this example:

const arr = ['one', 'two', 'three', 'four'];

const str = arr.join();

console.log(str);
// Output: 'one,two,three,four'

The join() method is not just limited to commas, you can pass any string as a separator to it and it will return you a string that contains each array element joined with the separator.

See this example:

const arr = ['one', 'two', 'three', 'four'];

const withSpaces = arr.join(' ');

console.log(withSpaces);
// Output: 'one two three four'

const withHypens = arr.join('-');

console.log(withHypens);
// Output: 'one-two-three-four'

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts