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

How to log property names using a for in loop?

I received the following message. There was an error with your code. Reference error. Can't find variable shanghai. * See code. If the challenge is asking to log 4 times, each value, wouldn't I have four lines of code, each with separate values; a line for population, a line for longitude, latitude, and country. And since shanghai is a city wouldn't the variable be city and not prop

script.js
var shanghai = {
  population: 14.35e6,
  longitude: '31.2000 N',
  latitude: '121.5000 E',
  country: 'CHN'
};

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

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! What we want is the properties of shanghai. And yes, you could have the name city to loop through your shanghai but it doesn't really make sense. The naming would suggest for every city in shanghai. But how many cities are generally in Shanghai? It'd make more sense if it were for cities in China, if you see what I mean.

Let's put it this way. What if the object were named toDoList? We could loop for toDoItem in toDoList. That to me makes sense as far as naming goes.

But the problem here isn't your variable. The problem here is that you're supposed to be logging to the console the keys. In this case what should be printed out to the console is "population" "longitude" "latitude" "country". Those are the keys. The values are ... well... a bunch of numbers for the coordinates and population and then CHN for the country.

Here's how I did it:

var shanghai = {
  population: 14.35e6,
  longitude: '31.2000 N',
  latitude: '121.5000 E',
  country: 'CHN'
};

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

Hope this helps! :smiley:

Thanks for your help. I understand the question better, now, with the answer you gave.