Javascript (ES6) const with curly braces

JavascriptEcmascript 6Constants

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontralstonView Question on Stackoverflow
Solution 1 - JavascriptDan PrinceView Answer on Stackoverflow