Search code examples
javascriptfirefoxsyntaxvariable-assignmentmozilla

Javascript - Assigning multiple variables to object properties using curly braces in variable declaration


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.


Solution

  • Looking at "Destructuring Assignment" links (i.e. http://en.wikipedia.org/wiki/JavaScript_syntax#Assignment and http://dailyjs.com/2011/09/12/destructuring/) it looks like this construct is destructuring assignment.

    Wikipedia:

    In Mozilla's JavaScript, since version 1.7, destructuring assignment allows the assignment of parts of data structures to several variables at once. The left hand side of an assignment is a pattern that resembles an arbitrarily nested object/array literal containing l-lvalues at its leafs which are to receive the substructures of the assigned value.

    In JavaScript arrays and objects are more or less the same so it is not very surprising that construct supported for arrays is also supported for objects.