Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,339 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,307 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.