javascriptarrayssyntax

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


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?


Solution

  • 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.