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

'Var' in 'For in' loops?

The video didn't specify using the 'var' keyword in the 'For In' loop, but all of a sudden it is needed during the challenge to pass. What gives? Are there times where 'var' is appropriate and and times when it is not? Here's the For In loop based on the video:

for (x in person) {
  console.log(x, ': ', person[x]);
}
script.js
var shanghai = {
  population: 14.35e6,
  longitude: '31.2000 N',
  latitude: '121.5000 E',
  country: 'CHN'
};

for (var property in shanghai){
  console.log (property);
}
index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript Objects</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>

2 Answers

Mat Morris
Mat Morris
10,292 Points

The for...in loop iterates over every property in arbitrary order. The reason it needs the var is so that it can set each property equal to your 'property' variable. It's replacing the variable with each property until it gets to the end of the array.

Here's some reading you can do on it:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Thanks Mat! That makes sense, but it doesn't explain why it worked without setting the variable in the video.