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 Loops, Arrays and Objects Tracking Data Using Objects Using `for in` to Loop Through an Object's Properties

im a little confused as to how you can name the variable in the 'for in' whatever you want 'prop in person)

he uses prop and says it can be anything, why doesnt it have to reference anything, i get that it is later referenced but how does this return all the information without specifically salling for anything except the entire object person

2 Answers

Andreas Nyström
Andreas Nyström
8,887 Points

Hi!

Let's see an example to examine this closer.

// Here I have an object called koala
let koala = {animal: 'Koala bear', cool: true, age: 22}; 

// Now I want to loop through all its properties (animal, cool & age).
// Prop is the property in the for...in-loop, and koala[prop] will give you the value of that property.

for (let prop in koala) {
  // Here I am console.logging the property first. In the first loop it should be animal, second it should be cool and so on.
  // Then I am adding the value after, I'm looking inside the koala-object and giving it 
  // the "key"-value of the property.

  // So first loop says in just strings "animal: Koala bear". Because the first property is animal. 
  // When I'm looking up the value its the same as saying koala[animal]
  console.log(prop + ': ' + koala[prop]);
}

Any clearer? If not maybe check how to search through an object using a "key"/"property".

If not, ask again! Good luck and happy coding :).

yes that helps, thank you. So it can be named whatever because it is for future reference, not referencing something already established?

Andreas Nyström
Andreas Nyström
8,887 Points

You can name it elephant or banana if you'd like. It's just a variable name holding the property of the object. But prop or property is pretty good I guess, since that is what it is :).

thank you!