Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to convert an array to a string

Short answer

The join() method glues the elements together with a separator:

console.log(['red', 'green', 'blue'].join(', '));

Output:

red, green, blue

JSON

JSON.stringify() suits data exchange and nested arrays:

console.log(JSON.stringify(['a', ['b', 'c'], 1]));

Output:

["a",["b","c"],1]

A list with and

Intl.ListFormat joins the elements the way people write lists, with and before the last one:

const list = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
 
console.log(list.format(['tea', 'coffee', 'juice']));

Output:

tea, coffee, and juice

Common mistake

Converting an array to a string without join() uses commas without spaces. Arrays of objects turn into useless text, so use JSON.stringify() for them:

console.log(String(['a', 'b', 'c']));
console.log(String([{ id: 1 }]));
console.log(JSON.stringify([{ id: 1 }]));

Output:

a,b,c
[object Object]
[{"id":1}]

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.