Written By

Sam

How to convert an Array into a Comma-Separated List in JavaScript

How to convert an Array into a Comma-Separated List in JavaScript

In this article, we'll cover how to convert an array into a comma-separated list in Javascript using either the toString() or join() methods.

Let's get it started!

toString()

We'll go over the toString() method first, which will result in the formation of a string concatenated by commas.

Here's what the code looks like:

const array = ["A", "B", "C", "D", "E"]

array.toString() // "A,B,C,D,E"

join()

The second method we'll go over is the join() method, which creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string.

Here's what the code looks like:

const array = ["A", "B", "C", "D", "E"]

array.join() // "A,B,C,D,E"

You can also customize the spacing between each item in the new string and what types of characters to use:

array.join(" ") // "A B C D E"
array.join(", ") // "A, B, C, D, E"
array.join(" and ") // "A and B and C and D and E"

Both the toString() and join() method is widely supported amongst different browsers and versions.

Happy coding!

Comments (0)

loading comments