JavaScript array to string (with and without commas)

Posted on Jan 14, 2021

Let's learn how to convert JavaScript array to string with or without commas. Example code included.

To convert a JavaScript array into a string, you can use the built-in Array method called toString.

The method will return a string that represents the elements stored in your array:

let numbers = [0, 1, 2, 3];
let numbersToString = numbers.toString();

// output is "0,1,2,3"

Keep in mind that the toString method can’t be used on an array of objects because it will return [object Object] instead of the actual values.

To convert an array of objects into a string, you need to use the JSON.stringify method:

let users = [
  { name: "John" },
  { name: "Lisa" },
  { name: "Jack" },
  { name: "Mary" },
let usersToString = JSON.stringify(users);

// [{"name":"John"},{"name":"Lisa"},{"name":"Jack"},{"name":"Mary"}]"

It’s not really a representation of the array values because the return value will still have the square and curly brackets, but it’s the best you can do with an array of objects.

JavaScript array to string without commas

Sometimes you may need to convert your array into a string without the commas. The toString method has no parameter, so you need to use join method instead.

join accepts one string parameter which will serve as the separator for your string:

[1, 2, 3].join(); // "1,2,3"
[1, 2, 3].join("+"); // "1+2+3"
[1, 2, 3].join(" "); // "1 2 3"

You can even pass an empty string to the method:

[1, 2, 3].join(""); // 123

And that’s how you turn a JavaScript array into a string.

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.