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
Jack Silcock
1,375 Pointsconst {dispatch, players} = this.props;
Can someone explain the goings on behind this line please? My guess this somehow sets players within props but not sure if this is correct or how this works if correct or what dispatch has to do with it?
Thanks, Jack
2 Answers
andren
28,558 PointsAs James mentions it is an example of object destructing. And it does not change the props, pretty much the opposite.
Object destructing is just a shorthand for pulling properties from an object into separate variables.
Let's say you had an object that looked like this:
const person = {
name: "Jack",
age: 25,
occupation: "Student"
}
If you for some reason wanted to create a name, age and occupation variable that held the value of those properties in the object how would you do that? Well in ES5 you would do this:
var name = person.name;
var age = person.age;
var occupation = person.occupation;
As you can see there is a decent amount of repetition in that code. Since it is somewhat common to create variable names that match the property name they are set equal to ES6 introduces a shorthand, which is what object destructing is.
Using that the above code can be turned into this:
const { name, age, occupation } = person;
That does the same thing as the code example above it. It tells JavaScript that you want to create three variables, and that their value should be set equal to properties within the object which are named the same as the variable name.
So in your code example:
const {dispatch, players} = this.props;
You are creating two variables (dispatch and players) and setting them equal to this.props.dispatch and this.props.players respectively.
james south
Front End Web Development Techdegree Graduate 33,271 Pointswithout more code it's hard to tell but maybe it's this:
Jack Silcock
1,375 PointsJack Silcock
1,375 PointsThat a brilliant explanation, thank you for the insight!