JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops The Refactor Challenge Solution

Josiah Baumgartner
Josiah Baumgartner
Full Stack JavaScript Techdegree Student 2,101 Points

Do you need to declare your counter variable in a for loop using 'var'?

I wrote my for loop in the challenge like this:

for ( i = 0; i < 10; i += 1) {

}

I forgot to write it as var i = 0; but it seems to work fine. Is there any issue to writing it as I did?

Edit: I was thinking about it more and maybe it works fine in this case but if there was another variable named i I think it would pull from global scope instead of just the loop parameters. Is that correct? It's probably best to be safe and use best practice all the time but please correct me if I am wrong.

1 Answer

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 81,699 Points

It is probably best to declare with let, actually as well as var. Not doing so may cause issues later on as your script gets bigger but as you suggest assigning the keywords or not as an effect on the scope of that variable. :-)

Steven Parker
Steven Parker
163,416 Points

To expand on what Jonathan is saying, if you omit "var" or "let" you're creating an implicit global variable, which you would generally want to avoid.

Josiah Baumgartner
Josiah Baumgartner
Full Stack JavaScript Techdegree Student 2,101 Points

I actually hadn't learned anything about the let keyword yet but your comment led me to do some research and it makes a lot of sense. Thanks!