Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Concatenate Array to String

I am using D3.js and often find myself dynamically building transform attributes (or d attributes on path elements). Both of these often require multiple comma-separated numbers.

Sometimes I build my strings by concatenating an array to string:

var x = 0,
y = 1,
path = 'M0,0 L' + [x, y];

And sometimes I build my strings by manually adding the comma:

var x = 0,
y = 1,
path = 'M0,0 L' + x + ',' + y;

I've decided that I should try to stick to one method or the other, and am wondering which approach is the better one to take.

Here are a few things I've considered:

  • I know that calling join() is slower than manually concatenating the commas, but is that what the browser does when it concatenates an array to a string?
  • The second format will work in any browser. Are there any browsers that don't support the first format?
  • The first format uses less characters (keeping file sizes low is always a plus).
  • Personally, I believe the first format is more readable.

Is there one way that is definitively better than the other? Or am I just being nitpicky?

like image 902
Towler Avatar asked Sep 27 '13 00:09

Towler


People also ask

How do I combine array elements into strings?

The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

Can you concatenate arrays in JavaScript?

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

Can you concatenate an array?

You can use the square bracket operator [] to concatenate or append arrays. For example, [A,B] and [A B] concatenates arrays A and B horizontally, and [A; B] concatenates them vertically.

How do you turn an array into a string?

In order to convert an array into a string in Javascript, we simply apply the toString() method on the given array, and we get a stringified version of our array. Internally javascript first converts each element into string and then concretes them to return the final string.


2 Answers

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.

like image 93
TenorB Avatar answered Sep 20 '22 16:09

TenorB


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.

like image 23
Nicolás Straub Avatar answered Sep 18 '22 16:09

Nicolás Straub