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 Tracking Data Using Objects Accessing All of the Properties in an Object

Christopher Borchardt
Christopher Borchardt
2,908 Points

whats 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
Karolin Rafalski
11,368 Points

If 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

Christopher Borchardt
Christopher Borchardt
2,908 Points

thank you, that makes sense. I knew there had to be a reason for it I just couldn't figure out what it was.

hector villasano
hector villasano
12,937 Points

var 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
Christopher Borchardt
2,908 Points

i'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
Pavithra Manivannan
7,474 Points

The 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.