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

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,119 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,860 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.