160

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.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
tralston
  • 2,825
  • 3
  • 19
  • 22
  • 4
    Here's an example, pretty good site when wanting to play with some ES6 stuff. http://www.es6fiddle.net/ih5zgb2r/ – ste2425 Nov 19 '15 at 08:36
  • 3
    ugh. how is `const {someKey} = someObj` a better alternative to `const someKey = someObj.someKey` – Zach Smith Aug 28 '18 at 11:06
  • @ZachSmith, it's a good alternative when you have multiple of them, such as `const {name, version, type} = app;` example in the accepted answer below. – Jaywalker Sep 26 '19 at 15:28
  • 1
    @jaywalker - yes. I pretty much use it constantly now – Zach Smith Sep 27 '19 at 05:59
  • personnel = { age: 45, sex: f, salary:2000 ... } const {salary, age, sex} = personnel same as const salary = personnel.salary const sex = personnel.sex const age = personnel.age – Akin Zeman Dec 13 '21 at 19:46

1 Answers1

305

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;
Dan Prince
  • 29,491
  • 13
  • 89
  • 120
  • i think your link is incorrect, hmm digest cycle. – ste2425 Nov 19 '15 at 08:37
  • 1
    You might want to add a link to MDN in your answer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment – Rūdolfs Vikmanis Nov 19 '15 at 08:38
  • For anyone who also writes PHP, this is kind of the equivalent of the [list()](https://www.php.net/manual/en/function.list.php) construct. – BadHorsie May 24 '21 at 14:01