Georgi Georgiev Georgi Georgiev - 8 months ago 41
Javascript Question

What do {curly braces} around javascript variable name mean

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

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?


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 in 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.