w3resource

JavaScript: Join all elements of an array into a string

JavaScript Array: Exercise-5 with Solution

Write a simple JavaScript program to join all elements of the following array into a string.

Expected Output:
"Red,Green,White,Black"
"Red,Green,White,Black"
"Red+Green+White+Black"

Sample Solution:

JavaScript Code:

// Declaration and initialization of an array
myColor = ["Red", "Green", "White", "Black"];

// Using the toString method to convert the array to a string
console.log(myColor.toString());

// Using the default join method to concatenate array elements into a string separated by commas
console.log(myColor.join());

// Using the join method with a custom separator ('+') to concatenate array elements into a string
console.log(myColor.join('+'));

Sample Output:

Red,Green,White,Black
Red,Green,White,Black
Red+Green+White+Black

ES6 Version:

// Declaration and initialization of an array
const myColor = ["Red", "Green", "White", "Black"];

// Using the toString method to convert the array to a string
console.log(myColor.toString());

// Using the default join method to concatenate array elements into a string separated by commas
console.log(myColor.join());

// Using the join method with a custom separator ('+') to concatenate array elements into a string
console.log(myColor.join('+'));

Live Demo:

See the Pen JavaScript - Join all elements of an array into a string- array-ex-5 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function to get the last element of an array.
Next: Write a JavaScript program which accept a number as input and insert dashes (-) between each two even numbers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.