There are 3 common ways you can convert any JavaScript array to string:

  • The built-in toString method to get all the array elements split by commas
  • The JSON.stringify function to get the JSON representation of a JavaScript array
  • The join method to use a custom separator

Transform JS array to a string with toString

To transform any JavaScript array to a string, you can use the built-in toString method

const fruits = ['apple', 'orange', 'mango'];

console.log(fruits.toString())

The array elements will be compiled to a string using a comma as a separator.

apple,orange,mango

Notice, that if you were to just pass the array “as is” into the console.log, then the output would have been different.

console.log(fruits); // [ 'apple', 'orange', 'mango' ]

Get a JSON string from any JS array with JSON.stringify

To get a JSON string from a JS array, you can pass it into the static function JSON.stringify.

const fruits = ['apple', 'orange', 'mango'];

console.log(JSON.stringify(fruits));

Each array element will be wrapped in double quotes.

["apple","orange","mango"]

Use join to transform JS Array to a string with a custom separator

To use a custom separator while transforming a JavaScript array to a string, you should use the join method.

const fruits = ['apple', 'orange', 'mango'];

console.log(fruits.join('-'));
console.log(fruits.join(' '));
console.log(fruits.join('\n'));

In the example above, I’m using three different separators: dash, space and newline character.

apple-orange-mango
apple orange mango
apple
orange
mango

Notice that the join method does not modify the original array.