Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 324
Navaneeth K N Avatar asked Feb 13 '13 07:02

Navaneeth K N


People also ask

Why do we need VAR in JavaScript?

In JavaScript, variables are used to hold a value. It can hold any value, from primitives to objects.

Why is var needed?

Risk managers use VaR to measure and control the level of risk exposure. One can apply VaR calculations to specific positions or whole portfolios or use them to measure firm-wide risk exposure.

Do I need to use var in js?

In Javascript, it doesn't matter how many times you use the keyword “var”. If it's the same name in the same function, you are pointing to the same variable. This function scope can be a source of a lot of bugs.

Why would you redeclare a variable in JavaScript?

Redeclaring a variable is useful in situations where it cannot be known if the variable has already been defined. By redeclaring a variable conditionally, as Google Analytics tracking code does, it allows for a variable to safely originate from more than one place.


1 Answers

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()
like image 146
davidchambers Avatar answered Oct 21 '22 23:10

davidchambers