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 trialMichael Helgesen
1,140 PointsThe var in for loop
Hi folks. Greetings from Norway. Total noob here trying to hang on with these loops. This may be a stupid question, but I would love to hear an explanation. I hope that helps me to learn better :)
My question is about the var in the for loop: for (var i = 0; i < 10; i += 1)
Why cant it be just like this: for (i = 0; i < 10; i += 1)
Thanks so much!
2 Answers
Dan Oswalt
23,438 PointsThat's a fine question. If you run a for loop without the var in the initialization, it will still work. Probably. The thing to know is the concept of scope. In the for loop, you are initializing the counter variable. Any time you are initializing a variable in javascript, you definitely want to use var to make sure that variable is assigned to the right scope. If you don't use var, the js interpreter doesn't know what scope to put it in, so it will guess and probably put it in the global scope, usually the window object, which isn't where you want it to be. You only want it to exist for the duration of your loop, you don't need it sticking around in the wrong scope, or you'll get unexpected results.
That's why I say that it might very well work, but why chance it? Does that make any sense?
james south
Front End Web Development Techdegree Graduate 33,271 Pointsi is a variable like any other and must be declared. you can also use let.
Michael Helgesen
1,140 PointsOf course! I see it now. That is a function scope ? Thanks so much for your answer.
Michael Helgesen
1,140 PointsMichael Helgesen
1,140 PointsAh, thank you so much for that excellent answer! I just thought of scope actually. It so many words and definitions to remember now in the start. That was really clarifying. Really appreciate it!