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
Adam Lyles Kauffman
14,016 Pointsdidnt understand es6 syntax or the equivalence
he said this es6 code
const { data } = require('../data/flashcardData.json');
const { cards } = data;
is equivalent to this code
const data = require('../data/flashcardData.json').data;
const cards = data.cards;
neither code makes much sense to me. the only thing i understand is in the first code block that { data } === {data: 'data'}. where is the require line being stored? what is data variable equal to and why do we set it equal to { cards }? also i dont understand why we are using dot notation in the second code block if there are no objects.
using the es6 code he accessed values in the object like so which doesnt make sense either
cards[0].question
``
1 Answer
Steven Parker
243,173 PointsThese are examples of destructuring assignment, which is a very cool feature but one that can be difficult to grasp.
Let's take this line from your conventional equivalent example:
const cards = data.cards;
So here, the "cards" property of the object named "data" is being used to initialize a new variable named "cards". So access to the property is being done on the right side of the assignment with dot notation. All standard so far. Now in the new syntax (using the full form instead of the abbreviated one above):
const { cards: cards } = data; // full form of: const { cards } = data;
Here's where the "destructuring" comes in. On the left side, the symbols we're used to using to put things into an object are being used to take something out of one. So "data" is the same object, but the code on the left is showing that we want to access the property inside it named "cards", and we want to put that value into a new const named "cards". Since the property name is the same as the variable we are creating, the property can be left off, which is what you had above.
For more details, see the MDN page on Destructuring assignment.
And your last example ("cards[0].question") is conventional notation, accessing a property named "question" on the first object (index 0) in an array of objects named "cards".
Steven Parker
243,173 PointsSteven Parker
243,173 PointsFor future questions, please provide a link to the course page when asking about something specific to a course element (video/challenge/quiz).