Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,883 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,883 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!