Search code examples
javascriptecmascript-6constants

JavaScript (ES6) const with curly braces


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

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?

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.


Solution

  • It's a destructuring assignment. Specifically, an object destructuring assignment.

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

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

    It's a shorthand way to initialise variables from object properties.

    const name = app.name;
    const version = app.version;
    const type = app.type;
    
    // Can be rewritten as:
    const { name, version, type } = app;
    

    You can do the same kind of thing with arrays, too.

    const a = items[0];
    const b = items[1];
    const c = items[2];
    
    // Can be written as:
    const [a, b, c] = items;