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 JavaScript Objects Loop Through Objects Use `for in` to Loop Through an Object's Properties

karan Badhwar
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
karan Badhwar
Web Development Techdegree Graduate 18,135 Points

object_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
Steven Parker
231,269 Points

In 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
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
karan Badhwar
Web Development Techdegree Graduate 18,135 Points

sir 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
Steven Parker
231,269 Points
// example when property is known before running:
person["name"]    // you could also use:   person.name
// example when property is NOT known:
person[prop]      // can't use dot notation for this
karan Badhwar
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
karan Badhwar
Web Development Techdegree Graduate 18,135 Points

But 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
Steven Parker
231,269 Points

The 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.