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 trialMegha Singh
6,146 PointsI tried the for in loop and it didn't work.
for (var pet in pets){ console.log(pet[name]); } This returned "undefined". Why?
Also, when I did html.concat(<h2>${pet.name}</h2>
) and logged it, it returned empty string, why is that?
1 Answer
Zaid Khan
12,769 PointsIt's returning undefined because you are trying to access the name by index(pet) of for loop.
If you want names from object pets, then this is how you loop and get the value by .name
for( let pet in pets){
console.log(pets[pet].name)
}
And to render on the page just cover the value of the name in the h2 element.
let html = '';
for( let pet in pets){
html += `
<h2>${pets[pet].name}</h2>
`
}
document.querySelector('main').innerHTML = html;
Zaid Khan
12,769 PointsZaid Khan
12,769 PointsAlso always try to wrap your code with 3 backticks (```) on the line before and after.