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

I'm completely stuck with loops.

I know what it's asking me to do, I just don't know how to combine all the stats to get the loop

script.js
var shanghai = {
  population: 14.35e6,
  longitude: '31.2000 N',
  latitude: '121.5000 E',
  country: 'CHN'
};
for (shanghai)
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

Mark Wilkowske
PLUS
Mark Wilkowske
Courses Plus Student 18,131 Points

Hi Kim, in the video segment before the quiz Dave says the for in loop is only for objects so it isn't quite like the other loops you learn in JavaScript 101 so syntax is the thing here.

I skip the workspaces and use a html doc and browser instead - quicker that way and I keep notes in the document - and in the console I found this just returns the property:

for (var something in shanghai){
    console.log(something);
}

This just returns the value:

for (var something in shanghai){
console.log(shanghai[something]);
}

For fun, this here puts the value before the property (if you'd ever want that?):

for (var something in shanghai){
console.log(shanghai[something] + ': ' + something);
}

But the answer is:

for (var something in shanghai){
    console.log(something + ': ' + shanghai[something]);
}

I got confused with this bit: shanghai[something] because it looks like another way of calling the property name but this is actually the exact syntax to call the value in a for in loop. Keep at it - success is just around the corner!

thank you mark

I don't understand how you can just create a new variable called something and target everything in it?

Cheo R
Cheo R
37,150 Points

Here's an example of using the for in loop.

for (var property1 in object1) {
  string1 += object1[property1];
}

So you're going to want your code to look like the above.