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 trialStephen Gough Jr
4,187 PointsHaving trouble understanding this loop
Hello again everyone. I don't understand how console.log(prop) would print just the property name to the console, but console.log(person[prop]) would print just the property value. Could someone explain this better? I understand that in for loops, the function goes over everything a certain amount of times (either set by us or just once for everything inside). I guess I also don't understand why we must use a new variable inside the for in loop. I admit the JavaScript course has been kicking my ass. My grasp of understanding started slipped toward the end of the array section, but I was hoping if I kept going forward things might get a little clearer.
2 Answers
Steven Parker
231,236 PointsThis concept is not related to loops (though it can be used in one). The "prop" variable is simply holding a string. so when you execute "console.log(prop)
" it displays the contents of that string.
Let's say the string is "name". so "person[prop]
" is using the bracket notation to access the "name" property of the "person" object. This would be equivalent to using the more common dot notation and writing "person.name
". The difference is the bracket notation allows the access using the contents of a variable instead of putting the actual property name in the code using the dot notation.
Does that clear it up?
Stephen Gough Jr
4,187 PointsYes, Steven, that did help me understand it a bit. I really appreciate your time to help me out, and I apologize for the late reply.