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 trialThomas Ma
15,199 PointsUse a for...in loop to log each of the property names of the composer object to the console.
help
const composer = {
name: 'Edward Ellington',
nickname: 'Duke',
genres: ['jazz', 'swing'],
instrument: 'piano'
};
2 Answers
Ryan Groom
18,674 PointsThomas 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
Full Stack JavaScript Techdegree Graduate 35,771 PointsYou 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) {...}
.
Thomas Ma
15,199 PointsI need the answer
shahzaib rafiq
Courses Plus Student 3,001 PointsHello, 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.
Brandon White
Full Stack JavaScript Techdegree Graduate 35,771 PointsBrandon White
Full Stack JavaScript Techdegree Graduate 35,771 PointsHi Thomas Ma,
What is it specifically that you need help with?
Do you not understand the for...in syntax? If so, hereโs a link to an article on how to use it.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in