175

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.

5
  • 4
    Here's an example, pretty good site when wanting to play with some ES6 stuff. es6fiddle.net/ih5zgb2r Commented Nov 19, 2015 at 8:36
  • 4
    ugh. how is const {someKey} = someObj a better alternative to const someKey = someObj.someKey Commented Aug 28, 2018 at 11:06
  • 1
    @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. Commented Sep 26, 2019 at 15:28
  • 2
    @jaywalker - yes. I pretty much use it constantly now Commented Sep 27, 2019 at 5: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 Commented Dec 13, 2021 at 19:46

1 Answer 1

325

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;
Sign up to request clarification or add additional context in comments.

3 Comments

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.