Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Tom Geraghty
Tom Geraghty
24,174 Points

Using ES6 data destructuring syntax is the opposite of traditional object literal syntax.

I wanted to mention this since it wasn't stated explicitly in the video on data destructuring in ES6.

In a normal variable assignment you take a value on the right of the equals sign and assign to a variable (named by you) on the left like this:

const myVariable = 'Some string value';

But in ES6 data destructuring the assignment to a named variable is backwards. This wasn't explcitly mentioned in the video and confused me the first time I ran into it so I wanted to add on to the video.

There's an excellent book on ES6 here: https://leanpub.com/understandinges6/read Chapter 6 is about destructuring. Of import here:

let node = {
        type: "Identifier",
        name: "foo"
    };
let { type: localType, name: localName } = node;
console.log(localType);     // "Identifier"
console.log(localName);     // "foo"

This code uses destructuring assignment to declare the localType and localName variables, which contain the values from the node.type and node.name properties, respectively. The syntax type: localType says to read the property named type and store its value in the localType variable. This syntax is effectively the opposite of traditional object literal syntax, where the name is on the left of the colon and the value is on the right. In this case, the name is on the right of the colon and the location of the value to read is on the left.

My 2c

Thanks! I did not know that!!

1 Answer

Steven Parker
Steven Parker
231,269 Points

It's not quite the opposite, and it's also not quite correct to say that the " the location of the value to read is on the left".

What you actually see on the left is the location of the value to read and name of the variable to write.

And while the structure appears to be the opposite visually, what follows the keys in a normal object literal assignment are values, but what follows the keys in a destructuring assignment are variable names.

Tom Geraghty
Tom Geraghty
24,174 Points

Steven you're everywhere lately! Do you just troll the forums for questions? F5 F5 F5! ;) Thanks for all the help, bud!