What do square brackets around an expression mean, e.g. `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 1:

Just in case anyone else arrives here while trying to find out what some weird/new syntax involving [square brackets] (seen in someone else's Javascript) might possibly be, like I was...

Nowadays, with ES6, we also have [] used on the left-hand side for destructuring arrays, e.g.

const names = ['Luke', 'Eva', 'Phil']; 
const [first] = names;  
console.log(first); // 'Luke' 
const [first, second] = names;  
console.log(first, second); // 'Luke' 'Eva'

For further info see http://www.deadcoderising.com/2017-03-28-es6-destructuring-an-elegant-way-of-extracting-data-from-arrays-and-objects-in-javascript/ or google 'es6 destructuring'.

Solution 2:

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.