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
Lee Cockcroft
5,147 PointsLoops through objects
Hi All,
Could someone explain this to me please, as looping objects just isnt sinking in!
ok, so firstly my for loop suggests the properties in obj, which will be a,b,c.
... var obj = {a:1, b:2, c:3};
for (var prop in obj) { console.log(obj[prop]) }
So if i console log(props), a,b,c is shown. now when i put obj[prop] why does this show the value? as surely im still saying "please display the object properties! which would be a,b,c! but this shows the values.
I might be completely wrong in what im saying, could someone please explain.
Thanks
2 Answers
andren
28,559 PointsIn a for loop the variable you define (named prop in the above example, but can be named whatever you want it to be) will be set to the name of the first property in the first loop, the name of the second property during the second loop and so on. So running your loop is exactly equivalent to this code:
console.log(obj[a]) // a is the first prop
console.log(obj[b]) // b is the second prop
console.log(obj[c]) // c is the third prop
When you write the name of an object and then a property in brackets you are telling Javascript to return the value of that property to you, and that is exactly what Javascript does.
Lee Cockcroft
5,147 PointsThank you for your help! I understand now :)