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

Why in for in loop don't we use var?

Hi guys, I don't understand why in the exampla Dave shows that the typical for in loop works in this way for (var key in student) { }

and in the example he uses the command without var for (prop in person { }

Why doesn't he uses the word var??

Thanks to all

2 Answers

Jacob Bergdahl
Jacob Bergdahl
29,118 Points

In Javascript, you can choose to not use the var keyword in a for in loop. However, it is usually best to use the var keyword and NOT do like the teacher did here. If you don't write var before the variable name, you create a global variable, which may not be preferable, as it could break the code. If you don't know what a global variable is, don't worry about it just yet. Just remember to use the var keyword, as it is indeed usually the best way to write a for in loop.

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,624 Points

Hey Luca,

Both variants will work, and I found a great forum thread that explains the different ways very nicely.

Hope that helps. :)

:dizzy:

I had the same question as OP, and found this link really helpful! Thanks for posting it.