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

With the code below I have reached the same result with less code, what are the advantages of the approach in the video?

// the objects //

const pet = [
  {name: 'Jesse', type: 'dog', breed: 'aussie', age: 0, photo: 'img/aussie.jpg'},
  {name: 'Luna', type: 'dog', breed: 'dachshund', age: 10, photo: 'img/dachshund.jpg'},
  {name: 'Toby', type: 'dog', breed: 'golden retriever', age: 5, photo: 'img/golden.jpg'},
  {name: 'Bickie', type: 'cat', breed: 'persian', age: 40, photo: 'img/persian.jpg'},
  {name: 'Tubby', type: 'rat', breed: 'tabby', age: 2, photo: 'img/tabby.jpg'}
]; 

// the code displaying the objects on the page // 

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

Can you wrap your code with 3 backticks (```) on the line before and after? That'll help us understand your code more clearly.

5 Answers

I see no problem with your code. There are numerous ways to achieve the same thing in programming. It's just about the cleaner approach, to store your stuff in a variable, so you may use it wherever you want.

Tbh, Abbie, I don't quite prefer using variables either. If the code is clear to you, then no need to use it. It just helps in better readability and maintenance when you have a thousand lines of code. If any expression needs a meaningful name, then you should use it.

Thank you!

Hi Zaid Khan , sorry, that was my first question so far, this looks better I hope

Nah, it's alright.

Is it considered best practice to store things in a variable? I wrote mine very similarly to Kylian and am realizing I use very few variables except for those that are directed in the challenge instructions. Should I be using more?

Hi Kylan, I'm new to coding - was just wondering if you could please explain how the code you used, selected the <main> element to display the content in? thanks