Alex Rivera | Logout

What does it do to concatenate a string to a bracketed expression, like `var x = "a" + [b]`?

Asked 2009-10-27T09:05:13.477
94

We have received some JavaScript from an agency that looks wrong, but works.

For some reason they are adding square brackets ([, ]) around variables, like this:

var some_variable = 'to=' + [other_variable];

This works, but the square brackets seem completely superfluous.

Is there a purpose of using this syntax or is it technically incorrect, but ignored by the browser?

Edit
Report

2 Answers

55

Square brackets means new Array.

var ar=new Array("a","b");
var ar=["a","b"]; //Equal to the syntax above

in that situation there's no difference if you use square brackets or not because if it's an array it is converted to string, but if you delete the brackets it takes less time because it doesn't have to build a new array and convert it but it works with a simple string.

answered 2009-10-27T09:10:39.503
9

I bet someone told that person:

  • "Do the string concatenation with an array, it's faster!"

Meaning:

var some_variable = ['to=', other_variable].join("");

Which is apparently faster for lots of concatenations, but totally irrelevant, as that code will probably run just once anyway. Premature_optimization = sqrt(all_evil)!

And the poor chap did that other irrelevant thing...

I love people.

answered 2009-10-27T09:28:40.870

Your Answer