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 React by Example Building the Application Changing Guest Name in State

Brian DeJesus
Brian DeJesus
3,183 Points

Why do we use "[property]: !guest[property]" when setting the state prop rather than "property: !property"?

in the "toggleGuestPropertyAt" function. Thanks ahead of time!

2 Answers

Abraham Juliot
Abraham Juliot
47,353 Points

[property] which can be ['anything'] is dynamic, meaning it can be any property on the guest object. So {property: !property} would not be dynamic. For instance, !property would be the same as !'whateverStringPropertyContains', which is always false, and false would always return an unchecked state, whereas here we need to toggle the boolean value.

Daniel Crittenden
Daniel Crittenden
9,308 Points

Brian,

The easiest way to understand this is to circle back to the concepts of extracting a value from an object using a key.

When trying to find the name of a guest, the actual code could be written the way that you described. However, you must remember that we are storing the property as a string. Therefore, what the computer is really seeing is:

"property": !"property"

The above syntax does not work. In these instances, we must use brackets to extract the value using a string variable.

You can read more here: https://javascript.info/object#square-brackets

Brian DeJesus
Brian DeJesus
3,183 Points

Thanks Daniel. This was so long ago it seems. Now, I have a better grasp of React and even Redux. I was very inexperienced with let alone javascript when I first started to get into React. It's great to see these forums still up for answers.