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 Using `for in` to Loop Through an Object's Properties

Bram Lo
Bram Lo
1,590 Points

Difference when creating a for-in loop with / without 'var'

Hi there,

I created my for-in loop using this code:

for(var key in person) {
  console.log(key, ': ', person[key]);
}

What this will print out when logging it to the console is:

  • name : Sarah
  • country : US
  • age : 35
  • treehouseStudent : true
  • skills : Array[3]

If I use the for-in loop like this (without var ):

for(key in person) {
  console.log(key, ': ', person[key]);
}

This will print out (which I actually want to be printed out):

  • name : Sarah
  • country : US
  • age : 35
  • treehouseStudent : true
  • skills : ["JavaScript", "HTML", "CSS"]

Can someone explain why this is happening? And when should I and shouldn't I use var to declare variables like key in an for-in loop.

Regards,

Bram

2 Answers

Wietse Wierda
Wietse Wierda
1,403 Points

1 reason I can think of why you should use var to declare the key variable is scope.

JavaScript Variable Scope and Hoisting Explained

Byron Glover
Byron Glover
5,772 Points

Hi Bram,

Just tested out your theory, got the same result both times in the skills properties, so not quite sure why that property is displaying two different ways for you.....

Also Wietse, isn't scope only something you would need to worry about if your For In loop was inside a Function???

Dhruv Patel
Dhruv Patel
8,287 Points

I believe scope applies to any programming construct defining its own variables. Wieste seems to be right about using var to declare the variable in the scope, but as long as you keep track of the variables, there is no problem in whichever way you want to use the for...in loop.