The method array.toString() actually calls array.join() which result in a string concatenated by commas. ref
var array = ['a','b','c','d','e','f'];
document.write(array.toString()); // "a,b,c,d,e,f"
Also, you can implicitly call Array.toString() by making javascript coerce the Array to an string, like:
//will implicitly call array.toString()
str = ""+array;
str = `${array}`;
Array.prototype.join()
The join() method joins all elements of an array into a string.
Arguments:
It accepts a separator as argument, but the default is already a comma ,
str = arr.join([separator = ','])
Examples:
var array = ['A', 'B', 'C'];
var myVar1 = array.join(); // 'A,B,C'
var myVar2 = array.join(', '); // 'A, B, C'
var myVar3 = array.join(' + '); // 'A + B + C'
var myVar4 = array.join(''); // 'ABC'
Note:
If any element of the array is undefined or null , it is treated as an empty string.
Browser support:
It is available pretty much everywhere today, since IE 5.5 (1999~2000).
References
- ECMA Specification
- Mozilla
- MSDN
In JavaScript, you can convert an array to a string with commas using the join()
method.
The join() method returns a string that concatenates all the elements of an array, separated by the specified separator, which in this case is a comma.
Here is an example:
const array = ['apple', 'banana', 'orange'];
const string = array.join(', ');
console.log(string);
// output: "apple, banana, orange"In this example, we first define an array of three fruits. Then we use the join()
method with a comma and a space as the separator to create a string that lists all the fruits with a comma and a space between each one.
You can replace the comma and space separator with any other separator you like, such as a hyphen, a semicolon, or a newline character.
It's important to note that the join() method only works on arrays, and it will throw an error if you try to use it on any other type of object.
Click here to learn more ways to Convert Array to String with Commas in JS
The method array.toString() actually calls array.join() which result in a string concatenated by commas. ref
var array = ['a','b','c','d','e','f'];
document.write(array.toString()); // "a,b,c,d,e,f"
Also, you can implicitly call Array.toString() by making javascript coerce the Array to an string, like:
//will implicitly call array.toString()
str = ""+array;
str = `${array}`;
Array.prototype.join()
The join() method joins all elements of an array into a string.
Arguments:
It accepts a separator as argument, but the default is already a comma ,
str = arr.join([separator = ','])
Examples:
var array = ['A', 'B', 'C'];
var myVar1 = array.join(); // 'A,B,C'
var myVar2 = array.join(', '); // 'A, B, C'
var myVar3 = array.join(' + '); // 'A + B + C'
var myVar4 = array.join(''); // 'ABC'
Note:
If any element of the array is undefined or null , it is treated as an empty string.
Browser support:
It is available pretty much everywhere today, since IE 5.5 (1999~2000).
References
- ECMA Specification
- Mozilla
- MSDN
Use the join method from the Array type.
a.value = [a, b, c, d, e, f];
var stringValueYouWant = a.join();
The join method will return a string that is the concatenation of all the array elements. It will use the first parameter you pass as a separator - if you don't use one, it will use the default separator, which is the comma.
Videos
The Array.prototype.join() method:
var arr = ["Zero", "One", "Two"];
document.write(arr.join(", "));
Actually, the toString() implementation does a join with commas by default:
var arr = [ 42, 55 ];
var str1 = arr.toString(); // Gives you "42,55"
var str2 = String(arr); // Ditto
I don't know if this is mandated by the JS spec but this is what most pretty much all browsers seem to be doing.
One option would be to pop the last item, then join all the rest by commas, and concatenate with and plus the last item:
const input = ['one', 'two', 'three', 'four'];
const last = input.pop();
const result = input.join(', ') + ' and ' + last;
console.log(result);
If you can't mutate the input array, use slice instead, and if there might only be one item in the input array, check the length of the array first:
function makeString(arr) {
if (arr.length === 1) return arr[0];
const firsts = arr.slice(0, arr.length - 1);
const last = arr[arr.length - 1];
return firsts.join(', ') + ' and ' + last;
}
console.log(makeString(['one', 'two', 'three', 'four']));
console.log(makeString(['one']));
Starting in V8 v7.2 and Chrome 72, you can use the sweet Intl.ListFormat API. It will also take care of localizing your list when requested, which might be of great help if you need it.
const lf = new Intl.ListFormat('en');
console.log(lf.format(['Frank']));
// โ 'Frank'
console.log(lf.format(['Frank', 'Christine']));
// โ 'Frank and Christine'
console.log(lf.format(['Frank', 'Christine', 'Flora']));
// โ 'Frank, Christine, and Flora'
console.log(lf.format(['Frank', 'Christine', 'Flora', 'Harrison']));
// โ 'Frank, Christine, Flora, and Harrison'
// You can use it with other locales
const frlf = new Intl.ListFormat('fr');
console.log(frlf.format(['Frank', 'Christine', 'Flora', 'Harrison']));
// โ 'Frank, Christine, Flora et Harrison'
You can even specify options to make it a disruption and use "or" instead of "and", or to format units such as "3 ft, 7 in".
It's not very widely supported as of writing, so you might not want to use it everywhere.
References
The Intl.ListFormat API - Google Developers
V8 release v7.2
When JavaScript coerces an array to a string, it actually call: .join(',') on the array. So you're actually going to be getting better performance with .join(',') manually as opposed to leaving it up to the interpreter to notice you're coercing the array. So: x + ',' + y is the fastest, [x, y].join(',') is the best practice(since it makes it easier to modify the behavior), and [x, y] is a tiny bit slower than manually calling .join and can be unreadable at times, but it's more convenient.
the short answer: use array.join.
the long answer:
First off, concatenation isn't faster than using array.join(), it's slower. this is because each time you concatenate you destroy two strings and create a new one.
take the following code:
<script>
function concat(){
var txt = '';
for (var i = 0; i < 1000000; i++){
txt =+ i + ',';
}
}
function arr(ar){
var txt = 'asdf' + ar;
}
ar = [];
for (var i = 0; i < 1000000; i++) {
ar.push(i);
}
concat();
arr(ar);
alert('done!');
</script>
and paste it into an html file. Then profile it. On my machine (core i7EE, 16GB RAM, SSD disks, IE9), arr() takes 0ms and concat() takes 12ms. Keep in mind this is over a million iterations (this same test would be quite different on IE6, concat() would take seconds).
Second, concatenation will take the same as array.join when having only two values. So for your example, from a performance perspective, they're both equivalent. if you take the above code and change the 1000000 to 4, both concat and arr take 0ms to execute. this means the difference for your particular flow is either inexistent or so negligible it doesn't show up in a profile.
Third, modern browsers optimize string concatenation using array.join() anyways, so the discussion is probably moot from a performance point of view.
That leaves us with style. Personally, I wouldn't use the first form because I don't like manually concatenating strings (when you've got 2 vars it's rather straightforward, but what if you have 10 vars? that'll make a really long line of code. And what if you receive an array with n values, in comes a for loop). I wouldn't use the second form either because, as pointed out in another answer, the value is coerced to a string, and that means some implicit transformation is going on. The problem here is the implicit part. I know now arrays are joined with a comma when coerced, but what happens if the spec changes, or some genius decides to change the toString implementation of Array.prototype in your codebase? just for fun run this in jsfiddle:
Array.prototype.toString = function() {
return 'not the expected result!';
}
alert([1, 2]);
Can you guess what the answer will be? (the above code will execute the same kind of conversion for the array as your code. coercion via the toString() method)
if you use array.join(','); you'll be futureproofing your code by stating that 1) your array will be joined regardless of the toString implementation and 2) it will be joined with a comma.