While looking at some Javascript code for Mozilla's (Firefox) Add-on SDK, I saw kind of variable declaration I hadn't seen before:
var { foo, bar } = someFunction("whatever"); // just an example
See those curly braces around the variable name? Turns out, this is a way of assigning the values of properties of an object to multiple variables all at once. It seems similar to destructuring assignment or PHP's list, except with object properties instead of arrays.
I actually found this out through some fiddling, since there appears to be no documentation on it. Take a look at this code:
function gimmeAnObject() {
return {
foo: "hey",
bar: "sup"
};
}
console.log(gimmeAnObject()); // Object { foo="hey", bar="sup" }
var { foo, bar } = gimmeAnObject();
console.log(foo); // hey
console.log(bar); // sup
I also found that this only works in Firefox. Chrome will instead throw an error: "Uncaught SyntaxError: Unexpected token {". That explains why I hadn't seen it before I started looking at Firefox add-on code.
Has anyone else seen this kind of variable declaration before? Why can't I find any documentation on it? Since it only works in Firefox, I'd think it might be a Mozilla thing, but I couldn't even find anything about it on MDN. Then again, maybe I just didn't know what to search for.