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, blueJSON
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 juiceCommon 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
- Array.prototype.join — Joins array elements into a string.
- JSON.stringify — Converts a value to a JSON string.