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

Brad Richardson
PLUS
Brad Richardson
Courses Plus Student 1,843 Points

i dont see what is wrong with my code

Use a for in loop to log each of the property names of the shanghai object to the console.

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

for (property in shanghai) {
  console.log(property, ':  ', shanghai[property]);
}

i get this error:

Bummer! It's a good idea to use the var keyword in a for in loop like this: for (var key in shanghai).

2 Answers

Sergey Podgornyy
Sergey Podgornyy
20,660 Points

As you can see on Warniing message:

Bummer! It's a good idea to use the var keyword in a for in loop like this: for (var key in shanghai).

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

To add on, you need to remember to use the "in" operator in the loop to iterate through the object. the "in" here iterates through the object, so you can access the objects properties.

Sergey Podgornyy
Sergey Podgornyy
20,660 Points

Do you explain this for me? My code works properly, you can check - https://jsfiddle.net/hf9yoako/

You don't to explain anything as you already did with your answer. I selected your answer as the best answer and was adding the information about the "in" operator to your answer, as that is the main focus of the for in loop.

Here is what the code should look like:

for(var prop in shanghai) { console.log(prop, ': ', shanghai['population']);

}