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

Chris Underwood
seal-mask
.a{fill-rule:evenodd;}techdegree
Chris Underwood
Full Stack JavaScript Techdegree Student 19,916 Points

var in the for for in loop in the video

I noticed in the video that Dave did not sure the var when he did the example for in loop. Like him, I was able to have my code work correctly without using var for the example. However, in the code challenge the system "recommended" using var. When should we use or not use var in for in loops?

Thanks,

Chris

3 Answers

Merritt Lawrenson
Merritt Lawrenson
13,477 Points

Using var to define a variable in a loop creates a variable within the scope of the loop only, while not using var changes or defines the variable globally, and can overwrite variables in other parts of the program if they share variable names. It's a best practice to use var, and then you'll never have to worry.

This concept is touched on elsewhere in Treehouse. I think this is the video about it:

https://teamtreehouse.com/library/javascript-basics-2/creating-reusable-code-with-functions/variable-scope

Michael M
Michael M
6,340 Points

Good question. This issue confused me as well when I was completing the challenge. I didn't use var keyword in the for in loop, so I failed the task. Maybe it's a good idea to explain the difference in the video tutorial?

Damien Watson
Damien Watson
27,419 Points

Hi Chris, Using 'var' makes the element a local variable, where not using the var looks up the chain to find the last declaration. Most cases this is fine, but it may lead to unexpected behaviour. The only time I have really had a problem was when using 'recursive loops', which is a bit more advanced than this course.

So the low down is if you want to make sure the variable is unique inside a function, use 'var'.