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 trialChristopher Borchardt
2,908 Pointswhats the point of var in the for in loop
I've been wondering this for a while, what does the var do in the for in loop? in the previous video the var was not typed in and it worked fine, but when i left the var off in the challenge it complained and said it was important to put it in. why is it important to have it in there?
4 Answers
Karolin Rafalski
11,368 PointsIf you forget to use var
, in many cases javascript will create a new variable for you. However, that variable could end up as a global variable and it may cause unexpected/hard to track bugs in larger programs.
Additionally, if you start using ECMAscript 6, you are required to run js in strict mode, which will not allow you to declare variables without var
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
hector villasano
12,937 Pointsvar is a keyword in javascript to declare a variable. Maybe that loop needed you to declare a variable before you called the statement.
Christopher Borchardt
2,908 Pointsi'm just a bit confused on why in a loop its said that its important to have it, when the loop runs exactly the same even if you don't have a var.
so basically if
for (prop in names){ console.log(prop); }
does the same thing as
for (var prop in names){ console.log(prop); }
what benefit is there to putting the var in at all?
Pavithra Manivannan
7,474 PointsThe keyword 'var' is used to declare the variable. In the for loop, we usually declare a variable and increment it. for ex: for(i=0; i<10; i++). In the previous video that you mentioned, the variable must have declared before.
Christopher Borchardt
2,908 PointsChristopher Borchardt
2,908 Pointsthank you, that makes sense. I knew there had to be a reason for it I just couldn't figure out what it was.