Array join() Method
Array to string conversion in JavaScript is achieved using the join()
method. The JavaScript Array join()
method joins all elements of an array and converts into a single string. The syntax is
array.join(separator)
The optional separator
parameter is some character to separate each element of the array in the returned string.
Consider the array ["Debian", "Fedora", "openSUSE", "Ubuntu"]. If we apply the typeof
operator on it,
> typeof ["Debian", "Fedora", "openSUSE", "Ubuntu"]; // object
it will return the string value "object"
. If the array calls the join()
method, the typeof
operator applied on it
> typeof ["Debian", "Fedora", "openSUSE", "Ubuntu"].join(); // string
will return the value "string"
.
We assign the above array to the variable os
and call the join()
method,
> var os = ["Debian", "Fedora", "openSUSE", "Ubuntu"];
> console.log(os.join());
which gives us a string of all elements of the array joined together, separated by a comma as a delimiter
Debian,Fedora,openSUSE,Ubuntu
Separator
If we pass the asterisk character (*
) as an argument into the join()
method
> var os = ["Debian", "Fedora", "openSUSE", "Ubuntu"];
> console.log(os.join('*'));
the resulting output in the browser console is a single string of joined array elements separated by the asterisk character (*
) as a delimiter
Debian*Fedora*openSUSE*Ubuntu