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 trialkaran Badhwar
Web Development Techdegree Graduate 18,135 Pointsobject_name.prop_Name or object_Name['prop_Name']
Isn't both the access properties same, but then why do only the bracket notation works.
Is it some sort of pre-defined way to access properties in for...in ?
One more thing when we access properties using [] notation we put property name as String, but over here we have directly included the key name via Variable (objectName[prop])? why so ?
2 Answers
Steven Parker
231,269 PointsIn the example that uses objectName[prop]
, the name "prop" is not a property name, but a string variable that contains a property name. The actual property name is not known before the program runs, which is why dot notation cannot be used in this case.
karan Badhwar
Web Development Techdegree Graduate 18,135 PointsBut sir in the loop we have mentioned that we are accessing the properties and the properties are defined before the loop runs so the doesn't that make the property known before hand only ?
What I have confusion is that when we use the objectName[prop] over here we are referencing to the the variable name, but why it cannot work with . dot notation, because we are just giving the reference to the variable that holds the property name
Steven Parker
231,269 PointsThe possible property names are known, but the specific property name being accessed changes with each loop pass. It's not just one property that can be known in advance, so dot notation cannot be used.
karan Badhwar
Web Development Techdegree Graduate 18,135 Pointskaran Badhwar
Web Development Techdegree Graduate 18,135 Pointssir can you please explain me this line I did not get it
"The actual property name is not known before the program runs, which is why dot notation cannot be used in this case"
Steven Parker
231,269 PointsSteven Parker
231,269 Points