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 Objects Loop Through Objects Loop Through an Object's Properties

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

help

script.js
const composer = {
  name: 'Edward Ellington',
  nickname: 'Duke',
  genres: ['jazz', 'swing'],
  instrument: 'piano'
};

2 Answers

Thomas Ma It is as simple as the following:

for (let property in composer) {
  console.log(property);
}

Where 'property' can be set to any name you see fit and 'composer' references the variable name of the object you created.

Brandon White
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brandon White
Full Stack JavaScript Techdegree Graduate 35,771 Points

You are correct, Ryan.

Although, youโ€™ll generally want to declare the โ€˜propertyโ€™ variable with either the let or const keyword. Otherwise, Iโ€™m pretty sure the variable gets defined on the global object (which is typically not what youโ€™ll want).

So typically itโ€™ll go for (let property in composer) {...} instead of for (property in composer) {...}.

I need the answer

shahzaib rafiq
PLUS
shahzaib rafiq
Courses Plus Student 3,001 Points

Hello, If you want to print the property name or key like 'name' and 'nickname' of the object composer by using 'for in' loop the syntax is for ( var propertyName in composer ){ console.log(propertyName); } this just gives you access to the key name.

However, if you want to access the property value like 'Edward Ellington' and 'Duke' you use "square bracket notation" Like for ( var propertyName in composer ){ console.log(composer[propertyName]); } in fact, the only way to access an object property using the 'for in' loop is with the bracket notation.