Join Together Array Items as a String in JavaSript
You can use any separator you want. In fact, the separator string can be anything at all, of any number of characters.
String with Just Commas
When you want just the comma character (
,) to appear as the separator between items in the list, use
.join(",") to convert the array to a string.
As you can see, there will never be an extra comma after the last item, meaning your entire array is now joined together as one string.
String with Comma and a Space
You can actually specify any separator you want to occur between the list items, so you can add both a comma and a space with
A list with commas and a space is definitely going to be more readable if it’s something you’re planning to look at on a screen.
.join() Is Comma No Space
If you just need a comma without a space, like when you’re creating a comma-separated values (CSV file) with values separated by one comma, then you can use
Array.prototype.join()) with no arguments:
.join() behavior is something you’d have to memorize. I recommend always using
.join(",") to help keep your code simple.
Special Cases When Joining Arrays with Commas
You can probably already guess what
.join() will return when you call it on an array with only one item in it: you get that item back as a string.
“If the array has only one item, then that item will be returned without using the separator.” — MDN Docs
If the array is empty, then you’ll get the empty string (
"") as the result of calling
.join()==="" // true.
0, the empty string is returned.” — MDN Docs
“If an element is
nullor an empty array
, it is converted to an empty string.” — MDN Docs
You could end up with extra commas when you don’t want them if you have any
undefined values in the array.
On the flip-side, maybe you do want missing items. If so, you can specify which items are missing with empty strings (
Join Together an Array as a String with Commas
.join(",") or equivalently just
.join() without any arguments at all. The result will always be a string.
A word to the wise is that
Array.prototype.join()) uses the “string conversions” of the items found in the array.
join():] The string conversions of all array elements are joined into one string.” — MDN Docs
If you’d rather your items be separated by a comma and a space, the syntax is:
.join(", "). But don’t use
.join("") with the empty string (
""), because that will return every item stitched together without a separator.
Happy coding! 👨🎤🌟👍🌞😊