Javascript

Convert Array to String in Javascript using Array.join()

Array.join() – With the help of the Array.join() method in javascript you can easily convert a Javascript Array into a string. In this example, we will learn how to use Array.join and how to convert arrays into a string in Javascript.

Also Read: Best Javascript Interview Question

What is Array.join() ?

Array.join() method is an inbuilt function in JavaScript which is used to join the elements of an array using anything separating the elements of am array, usually, it is an ‘,’.

By default, it adds a comma to resulting values, though you can also specify that it adds nothing or some other separator value.

Syntax of Array.join() Method.

array.join(separator)

Here, Array refers to an array that you want to join and the separator is an optional value that can either be used as a parameter or not. Its default value is comma(, ).

Convert Array into String in Javascript?

Now, let’s talk about the main part of the post i.e converting an array into string in javascript. Let’s understand this with the help of an example.

const alphabets = ['a', 'b', 'c']
const joinedString = alphabets.join('')
console.log(joinedString)
// Output
'a,b,c'

Other methods to convert an array into string in Javascript

Javascript provides many more methods to convert an array into strings besides the array.join() method. let’s have a look.

Use Javascript inbuilt toString() Method

['a', 'b', 'c'].toString(); // 'a,b,c'

You can also use JavaScript’s type coercion: the + operator can either add two numbers or concatenate two strings. But it must be noted that whenever you try to join an object (an array [] is also an object) with something else, JavaScript won’t crash our program, instead, it does know how to concatenate strings, so it will convert everything into a string.

However, this method is not the correct way of doing things but it works though. Here is an example of the same.

['a', 'b', 'c'] + []; // 'a,b,c'
['a', 'b', 'c'] + ''; // 'a,b,c'

Use Javascript JSON.stringify() method

JSON.stringify(['a', [1], 'b', 'c']); // '['a', [1], 'b','c']'

So, that’s all about it and this is how you can convert an array into string in javascript.

Leave a Comment