Javascript (ES6) const with curly braces

tralston picture tralston · Nov 19, 2015 · Viewed 36.6k times · Source

I'm new to ECMAScript 6, and while trying to learn Ember, I've seen the following code style occassionally:

const {
  abc,
  def
} = Object;

I've searched Google and many sites explaining the new ES6 specifications. I know this is not the current implementation, because my console gives an error when I input that.

What does this code mean?

UPDATE

I pasted this snippet into Babel's transpiler, and this is what it returned:

"use strict";

var abc = Object.abc;
var def = Object.def;

I'm still confused as to what this is trying to accomplish.

Answer

Dan Prince picture Dan Prince · Nov 19, 2015

It is an ES2015 destructuring assignment. More specifically, it's Object Destructuring

It might help to see it rewritten in a more verbose way.

const abc = Object.abc;
const def = Object.def;

It's a syntatically terse way of extracting properties from objects, into variables.

// you can rewrite this
const name = app.name;
const version = app.version;
const type = app.type;

// as this
const { name, version, type } = app;

Browser vendors are still implementing the ES2015 specification which is probably why it didn't work in your browser.

However, there's a project called Babel which allows you to convert future specifications of Javascript back into ES5. You can try out ES2015 code in their REPL.