Not sure if this is a Mozilla-specific JS syntax, but I often found variables being declared this way, for example, in add-on SDK docs:
var { Hotkey } = require("sdk/hotkeys");
and in various chrome Javascript (let
statement is being used in place of var
),
let { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
I found it very confusing but I am not being able to find any documentation about both syntax, even on MDN.
They're both JavaScript 1.7 features. The first one is block-level variables:
The second one is called destructuring:
For those familiar with Python, it's similar to this syntax:
The first code chunk is shorthand for:
You can rewrite the second code chunk as:
There is documentation for the
let
statement on MDN: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/letlet
is similar tovar
in that it limits the scope of the declared variable. It allows you to declare a variable inside aif(){}
block (or some other block) and have that variable only "visible" inside that block (JavaScript, until now, has function scope and not block scope as most other languages). So thelet
is basically a "fix" for something many people have issues with. Note that tihs is a JavaScript 1.7 feature.Haven't found anything on
{Foo}
.What you're looking at is a destructuring assignment. It's a form of pattern matching like in Haskell.
Using destructuring assignment you can extract values from objects and arrays and assign them to newly declared variables using the object and array literal syntax. This makes code much more succinct.
For example:
The above code is equivalent to:
Similarly for arrays:
This is equivalent to:
You may also use
let
to extract as well as rename an object property as follows:This is equivalent to:
That's all there is to it.