Explain Codes LogoExplain Codes Logo

Easy way to turn JavaScript array into comma-separated list?

javascript
array
string-manipulation
functions
Anton ShumikhinbyAnton Shumikhin·Sep 26, 2024
TLDR

To transform an array into a comma-separated string, use join(','):

let arrToStr = [1, 2, 3].join(','); // Outputs: "1,2,3", feels almost like magic!

The join() function is your handy tool for merging array elements into a single, cohesive string.

Array to string: consider data types

Regardless of the data types in your array, .join() will combine them into a single string:

let mixedArray = ['Alice', 42, true].join(','); // And here we witness the happy union of Alice, 42, and "truth" in string format.

Even if your array contains complex data structures like objects or other arrays, .join() still does the job:

let complexArray = [{name: 'Alice'}, [1, 2], function() {}].join(','); // Beware: This outputs "[object Object],1,2,function() {}", sounds like a weird potion recipe but that's JavaScript!

Join with any separator

You can make .join() function even more flexible by using any separator of your choice:

let arrToStr = ['Red', 'Green', 'Blue'].join(' | '); // Outputs "Red | Green | Blue", because colors deserve aesthetic separation.

Alternatives to .join()

Using toString()

You can call .toString() on an array for a comma-separated value (CSV) output:

let arr = [4, 5, 6]; console.log(arr.toString()); // Welcome to the world of strings, "4,5,6"!

Casting with String()

Calling String() on an array leads to a comma-separated string, similar to .toString():

console.log(String([7, 8, 9])); // "7,8,9", and we've successfully avoided math.

Browser consistency

Using .join() or .toString() guarantees consistent output across different web browsers providing reliability for your script.

Dealing with null and undefined

Use .join() with caution when your array might contain null or undefined values:

let trickyArray = [null, 'apple', undefined, 'banana']; console.log(trickyArray.join(',')); // Outputs ",apple,,banana", two commas don't make it a fruit salad!