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 Display an Array of Objects on the Page – One Solution

My solution using the for...in loop

let name;
let type;
let breed;
let age;
let photo;
let main = document.querySelector('main');

for (let prop in pets) {
  name = pets[prop].name;
  type = pets[prop].type;
  breed = pets[prop].breed;
  age = pets[prop].age;
  photo = pets[prop].photo;
  main.innerHTML += `
  <h2>${name}</h2>
  <h3>${type} | ${breed}</h3>
  <p>Age: ${age} </p>
  <img src=${photo} alt=${breed}>
`
}

1 Answer

Jamie Moore
Jamie Moore
3,997 Points

Whilst this code will work perfectly fine, I think declaring variables for each bit of data is a little overkill. You could just skip the variable declerations and access the properties where you need them. That way, your for loop becomes a bit more compact and easier to manipulate in the future.

for (let prop in pets) {
    main.innerHTML += `
       <h2>${pets[prop].name}</h2>
       <h3>${pets[prop].type} | ${pets[prop].breed}</h3>
       <p>Age: ${pets[prop].age} </p>
       <img src=${pets[prop].photo} alt=${pets[prop].breed}>
    `;
}

This is only my opinion though, so feel free to disagree!