What do square brackets around an expression mean, e.g. `var x = a + [b]`?
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'.
Even without changing the Array
prototype there are differences:
var other_variable;
var some_variable = 'to=' + [other_variable];
If other_variable
is undefined
, the return value with the array is "to="
.
Without the array, the return value is "to=undefined"
.
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.
b = "bar" + ["foo"]
This is syntactically correct, but indeed very, very, superfluous. This is how it works:
["foo"]
JavaScript takes the string "foo" and converts it to an array with one element, "foo":
"bar" + ["foo"]
when +
is used, and one of the operands is a string, "bar" in this case, JavaScript converts the second one to a string. Since operand two is an Array, the Array.toString
method is called, which, by default, returns all elements joined by a comma. We have one element, and the result will be equal to this element, i.e., in this context "foo"
is equivalent to ["foo"]
.
If you redefine Array.toString
you can see better what's going on:
alert("bar" + ["foo"])
Array.prototype.toString = function() { return "???"; }
alert("bar" + ["foo"])