This post will discuss how to print the contents of an array separated by comma in JavaScript.

Here are some examples of how to print the contents of an array separated by comma in JavaScript given an array:

1. Using Array.join() function

The Array.join() function joins all elements of an array into a string and returns the new string. The elements of the array will be separated by a specified separator. We can use it to print contents of an array separated by comma by passing a comma as an argument to the function. For example, if we have an array [1, 2, 3, 4, 5] and we want to print it as a string with commas, we can do:

Download  Run Code

 
We can also use other separators such as spaces, dashes, or any other characters. This is a common and flexible way to print contents of an array separated by comma in JavaScript for formatting or styling purposes. We can even modify or format the array elements as needed. For example, the following code invokes the toUpperCase() function on each array element using the map() function, before joining them together with the join() function.

Download  Run Code

2. Using Array.toString() function

The Array.toString() function converts an array into a string and returns the new string. The elements of the array will be separated by a comma by default. It is equivalent to calling the join function without any arguments. For example:

Download  Run Code

 
This is a simple and convenient way to print contents of an array separated by comma in JavaScript for debugging or displaying purposes.

3. Using Array.reduce() function

The Array.reduce() function applies a function to each element of the array, accumulating the result in a single value. The function can use the ternary operator to check if the current element is the last one, and append a comma or not accordingly. For instance:

Download  Run Code

4. Using for loop

This method involves using a for loop to iterate over the array from the start to the end, and concatenates each value into a string with embedded expressions. The function can use the loop index variable to check if the current element is the last one, and append a comma or not accordingly. For instance:

Download  Run Code

That’s all about printing the contents of an array separated by comma in JavaScript.