13

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?

Navaneeth K N
  • 15,295
  • 38
  • 126
  • 184
  • Don't know myself, but this might have some information for you: http://stackoverflow.com/questions/4445496/curly-bracket-variable-in-javascript – CodeMoose Feb 13 '13 at 07:19

1 Answers1

14

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()
davidchambers
  • 23,918
  • 16
  • 76
  • 105
  • I'm familiar with the concept from CoffeeScript: http://coffeescript.org/#destructuring. I believe ECMAScript may adopt something similar (which is why it may already be appearing in Firefox add-ons). – davidchambers Feb 13 '13 at 07:24
  • Thanks. Destructing assignment sounds interesting. However, I don't see a similar example like `var {Hotkey} = require('sdk/hotkeys');` in the documentation link that you have pointed to. – Navaneeth K N Feb 13 '13 at 08:22
  • 2
    `var {op: a} = getASTNode()` is equivalent to `var a = getASTNode().op`. The token to the left of the ":" is the property name and the token to the right of the ":" is the variable name. Often, though, one wishes to use the same name in both cases, as in `var {Hotkey: Hotkey} = require('sdk/hotkeys')`. Because this is a common pattern, there's a shorthand: `var {Hotkey} = require('sdk/hotkeys')`. – davidchambers Feb 13 '13 at 09:15
  • destructuring has been around in Mozilla's enhanced versions of JS for a long time - there are a number of Mozilla-specific extensions to JS that are also finding their way into Harmony such as array comprehensions and generators. – therealjeffg Feb 13 '13 at 14:30