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 Simplify Repetitive Tasks with Loops The Refactor Challenge Solution

Jerry Wu
Jerry Wu
1,845 Points

Why is it necessary to declare 'i' as a variable?

For this challenge, 'The Refactor' Challenge', it seems that it makes no difference whether I declare i as a variable or not in the for loop. (i = 0; i<10; i += 1) versus (var i = 0; i<10; i += 1).

Why is this? Is it just a generally better practice to declare i as a variable? Is there an example of what kind of problems I may run into if I do not declare i as a variable?

2 Answers

Steven Parker
Steven Parker
231,275 Points

Assigning a variable by using only the name causes an implicit global declaration. In the main program, this will not be functionally different from using "var", but it is considered bad practice.

Also, if the JavaScript engine is in strict mode, implicit declaration is not allowed and will cause an error.

Leopold Lucas
Leopold Lucas
17,236 Points

I think it is just standard practice. You can put whatever you want as a variable within a for loop. It is generally unnecessary to name it something different because there is block level scoping with let as opposed to var.