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 for loop not looping

const pets = [
  {name: 'Gohan', type: "dog", breed: 'golden', age: 4, photo: 'img/golden.jpg' },
  {name: 'nala', type: "dog", breed: 'pug', age:3 , photo: 'img/persian.jpg' },
  {name: 'Polo', type: "dog", breed: 'tabby', age: 105, photo: 'img/pug.jpg'}
];



let hmtl = '';

for(let i = 0; i < pets.length; i++){
  let name = pets[i].name;
  let type = pets[i].type;
  let breed = pets[i].breed;
  let age = pets[i].age;
  let photo = pets[i].photo;
 html = `<h2>${name}</h2><h3> ${type}| ${breed}</h3><p>Age: ${age}</p><img src= '${photo}' alt="${type}">'`;
};

console.log(html);

document.querySelector('main').innerHTML = html;

When I try to view the content it only shows the result for the final object. I am not sure why my loop does not start from zero.

1 Answer

html is misspelled in let hmtl = '';, and html = `<h2>${name}</h2><h3> ${type}| ${breed}</h3><p>Age: ${age}</p><img src= '${photo}' alt="${type}">'`; should be html += `<h2>${name}</h2><h3> ${type}| ${breed}</h3><p>Age: ${age}</p><img src= '${photo}' alt="${type}">'`; with += instead of = to keep previous values.