Search code examples
javascriptfirefoxcoding-stylefirefox-addon-sdk

Why use var { VariableName } = require('') in javascript?


I have seen lot of examples in Firefox addon-sdk which uses the below style when declaring a variable.

var { Hotkey } = require("sdk/hotkeys");

What difference it makes with var { Hotkey } than using var HotKey? Why the extra flower brackets are used?


Solution

  • This is destructuring assignment.

    var {Hotkey} = require('sdk/hotkeys');
    

    is equivalent to:

    var Hotkey = require('sdk/hotkeys').Hotkey;
    

    See also the harmony:destructuring proposal, which includes the following examples:

    // object destructuring
    var { op: a, lhs: b, rhs: c } = getASTNode()
    
    // digging deeper into an object
    var { op: a, lhs: { op: b }, rhs: c } = getASTNode()