w3resource

JavaScript: Join all elements of an array into a string

JavaScript Array: Exercise-5 with Solution

Join Array Elements

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('+'));

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.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that joins all elements of an array into a string using a specified separator.
  • Write a JavaScript function that converts an array to a string and handles nested arrays by flattening them first.
  • Write a JavaScript function that joins array elements with a default comma separator if none is provided.
  • Write a JavaScript function that properly handles empty arrays and non-string elements during the join operation.

Go to:


PREV : Last Elements of Array.
NEXT : Insert Dashes Between Evens.

Improve this sample solution and post your code through Disqus.

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.