What do {curly braces} around javascript variable name mean

JavascriptFirefoxFirefox Addon

Javascript Problem Overview


EDIT After looking at JSHint I found this 'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz) and this however after reading it I still don't understand why it is used

I have come across the following code on [MDN][2]

var ui = require("sdk/ui");
var { ActionButton } = require("sdk/ui/button/action");

What do the braces on the second line do and why are they used? Why are there no braces on the first line?

[2]: https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/ui "MDN"

Javascript Solutions


Solution 1 - Javascript

This is what's known as a destructuring assignment, and it's a new feature of JavaScript 1.7 (and ECMAScript 6) (Currently, only available as part of the Firefox JavaScript engine.) Roughly, it would translate into this:

var ActionButton = require("sdk/ui/button/action").ActionButton;

It seems silly in this example, as there's only one item being assigned. However, you'd be able to use this pattern to assign multiple variables at once:

{x, y} = foo;

Is the equivalent to:

x = foo.x;
y = foo.y;

This can also be used for arrays. For example, you could easily swap two values without using a temporary variable:

var a = 1;
var b = 3;

[a, b] = [b, a];

Browser support can be tracked using kangax' ES6 compatibility table.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGeorgi GeorgievView Question on Stackoverflow
Solution 1 - JavascriptMike ChristensenView Answer on Stackoverflow