How to Convert Array to String in JavaScript

There are the following ways to convert an array to string in JavaScript.

  1. Using the Array.prototype.toString()
  2. Using the Array.prototype.join()
  3. Using the Array.prototype.reduce()
  4. Using the Array.prototype.map()

Method 1: Using the Array.prototype.toString()

To convert an array to string in JavaScript, you can use the “toString()” method. The “toString()” is a built-in method that concatenates all elements of the array with a comma “,” as the separator.

Example

const arr = ['bmw', 'audi', 'mercedez'];

const str = arr.toString();

console.log(str);

Output

bmw,audi,mercedez

Method 2: Using the Array.prototype.join()

The join() is a built-in JavaScript method that concatenates all elements of an array into a single string. You can provide an optional separator that will be placed between the elements. If no separator is provided, a comma , will be used as the default separator.

Example

const arr = ['apple', 'banana', 'cherry'];

const str = arr.join(); 

const strWithSeparator = arr.join(' - ');

console.log(strWithSeparator)

Output

apple - banana - cherry

Method 3: Using the Array.prototype.reduce()

JavaScript array reduce() is a higher-order function that can accumulate an array’s elements into a single value. You can use the reduce() method to build a custom string representation of an array.

Example

const arr = ['bmw', 'audi', 'mercedez'];

const str = arr.reduce((accumulator, currentValue) => 
                        accumulator + ', ' + currentValue);

console.log(str)

Output

bmw, audi, mercedez

Method 4: Using the Array.prototype.map()

You can use template literals (enclosed by backticks) and map() to create a custom string representation of an array with a specific format.

const arr = ['bmw', 'audi', 'mercedez'];

const str = arr.map(item => `[${item}]`).join(', ');

console.log(str)

Output

[bmw], [audi], [mercedez]

Each of these methods has its own advantages and use cases.

The join() and toString() functions are straightforward and work well for simple conversions, while reduce() and map() offer more flexibility and control over the resulting string format. Choose the method that best fits your needs for converting an array to a string.

That’s it.

Leave a Comment