How to Convert an Array to String with Spaces in JavaScript?

To convert an array to a string with spaces in JavaScript you can use the Array.join() method. The join() method concatenates the elements of the array with the specified separator string and returns the concatenated elements as a new string.

This means we have to pass a string containing a space to the join() method as a parameter and it will return us a string containing all array elements joined with a space character.

See the following example:

const arr = ['one', 'two', 'three', 'four'];
const str = arr.join(' ');

// Output: 'one two three four'

console.log(typeof str);
// Output: string

If you don’t pass any separator to the join() method, it will join the array elements with a comma(,).

const arr = ['one', 'two', 'three', 'four'];
const str = arr.join();

// Output: 'one,two,three,four'

If you want to convert the array to a string with any other separator string, you can directly pass it to the join() method. And it will give you the desired result.

See this example:

const arr = ['one', 'two', 'three', 'four'];
const withHypens = arr.join('-');
console.log(withHypens) // 👉 'one-two-three-four'

const withCommas = arr.join(', ');
console.log(withCommas); // 👉 'one, two, three, four'

const withoutSpace = arr.join('');
console.log(withoutSpace); // 👉 'onetwothreefour'