Javascript (ES6) const with curly braces

51,050

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;
Share:
51,050
tralston
Author by

tralston

Updated on July 08, 2022

Comments

  • tralston
    tralston almost 2 years

    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.

  • ste2425
    ste2425 over 8 years
    i think your link is incorrect, hmm digest cycle.
  • Rūdolfs Vikmanis
    Rūdolfs Vikmanis over 8 years
    You might want to add a link to MDN in your answer: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • BadHorsie
    BadHorsie about 3 years
    For anyone who also writes PHP, this is kind of the equivalent of the list() construct.