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

Josiah Baumgartner
Josiah Baumgartner
Full Stack JavaScript Techdegree Student 3,185 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.

2 Answers

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 82,447 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
171,375 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 3,185 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!

Mareks Zevalds
Mareks Zevalds
2,997 Points

Hi all!

I was looking if someone asked a similar question to mine, and it looks like Josiah has. In my case, I realised that I did not declare variable rgbColor as seen here:

var html = '';

function randomColour() { var colour = Math.floor(Math.random() * 256); return colour; }

for ( var i = 0; i < 10; i += 1) { rgbColor = 'rgb(' + randomColour() + ',' + randomColour() + ',' + randomColour() + ')'; html += '<div style="background-color:' + rgbColor + '"></div>'; }

document.write(html);

I commented out variable html and it threw an error. However, not declaring rgbColor does no harm. Why is that? Based on the discussion - is it then rgbColor an implicit global variable? But then why is html not?

Thanks in advance!

Mareks Zevalds
Mareks Zevalds
2,997 Points

I just realised, that it is probably due to html being redefined (is that the right term), not assigned. Therefore, rgbColor is implicitly defined because it is an assignment, whereas html isn't (within the for loop).