Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.