To convert an array to a string with spaces in JavaScript, call the join()
method on the array, passing a string containing the space as an argument. For example:
const arr = ['coffee', 'milk', 'tea'];
const withSpaces = arr.join(' ');
console.log(withSpaces); // coffee milk tea
The Array
join()
method returns a string containing each array element concatenated with the specified separator. If no separator is passed as an argument, it will join the array elements with commas:
const arr = ['coffee', 'milk', 'tea'];
const str = arr.join();
console.log(str); // coffee,milk,tea
We can specify other separators apart from a space, like hyphens and slashes:
const arr = ['coffee', 'milk', 'tea'];
const withHypens = arr.join('-');
console.log(withHypens); // coffee-milk-tea
const withSlashes = arr.join('/');
console.log(withSlashes); // coffee/milk/tea
A separator can also contain more than one character. This allows us to separate the array elements with words or multiple spaces. For example:
const arr = ['coffee', 'milk', 'tea'];
const withAnd = arr.join(' and ');
console.log(withAnd); // coffee and milk and tea
const withOr = arr.join(' or ');
console.log(withOr); // coffee or milk or tea
const with2Spaces = arr.join(' ');
console.log(with2Spaces); // coffee milk tea
Note: If an element in the array is undefined
, null
, or an empty array ([]
), it will be converted to an empty string (''
) before concatenation with the separator. For example:
const arr = ['coffee', null, 'milk', []];
const withComma = arr.join(',');
console.log(withComma); // coffee,,milk,
const withSpaces = arr.join(' ');
console.log(withSpaces); // coffee milk
Every Crazy Thing JavaScript Does
A captivating guide to the subtle caveats and lesser-known parts of JavaScript.