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

Teacher Russell
Teacher Russell
16,873 Points

Using 'for in' to loop through an object

This video's notes point out that they forgot to add the var to the for in loop....for (var prop in person) {} I noticed this, too, but tried before I read the notes, and it still runs. Is this jsut a best practice, or will it cause problems when writing to places other than the council? Thanks!

1 Answer

andren
andren
28,558 Points

It is considered a bad practice, and if you are writing JavaScript in an environment that enforces Strict mode then it would actually not work.

When you don't add var before the variable the variable will automatically be created as a global variable, even if the variable is created within a function. Meaning that it exists in all functions in all JS files loaded on the site. Use of global variables are generally discouraged since it makes naming conflicts and bugs more likely to occur.

When you do add var the variable will only exist within the function it was created in. Since the loop you are writing in this video is not placed within a function the variable would actually end up as a global variable even if you did use the var keyword. So in this specific case it actually doesn't change anything, but being explicit when creating a variable is still considered good practice.

Teacher Russell
Teacher Russell
16,873 Points

I totally understand, and totally agree! Thanks for the quick reply.