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

Colin Taylor
Colin Taylor
3,341 Points

Why does 'prop' or any other variable work?

I can't understand why the variable created in the loop (prop) works to log all the properties. It's just a variable that is created and is empty, so I don't get while just writing

console.log(prop);

would log anything at all. Thanks in advance ya'll.

1 Answer

Kevin Korte
Kevin Korte
28,149 Points

It's the way that a for in loop works in Javascript. It's always going to be a for (variable in object) { ... }, so no matter what you set as your variable keyword (in the video it was prop), that variable keyword is always going to be filled with the property name of the object. This loop is very specific to looping through an array.

That's why it gets filled with prop values. The JS interpreter is doing that, because that is inherently how that function works in Javascript.

Here is another great resource: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in