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 trialJanelle Mackenzie
7,510 PointsWhy is the HTML variable declared outside of the for loop rather than inside?
Why is the HTML variable declared outside of the for loop rather than inside?
1 Answer
Grant Polhemus
7,093 PointsBecause if we declare the HTML variable within the for loop then it'll be on the local scope. That means we'd only be able to use it while we're inside of that for loop. Other parts of the script that aren't part of that block won't be able to "see" it.
By declaring it outside of the loop, it's on the global scope. That means it's visible to the entire script, and we can use it after the loop has finished running.
The program still runs if you declare the HTML variable inside of the loop, but I think it's bad practice because chances are you're going to use that HTML variable in other parts of your script, so it's best to declare it once on the global scope rather than every single time you need it.
Bad:
for (let i = 0; i < pets.length; i++) {
let html = ''; // Local Scope
let pet = pets[i];
html += `
<h2>${pet.name}</h2>
<h3>${pet.type} | ${pet.breed}</h3>
<p>${pet.age}</p>
<img src="${pet.photo}" alt="${pet.breed}">
`;
document.querySelector('main').insertAdjacentHTML('beforeend', html);
} // End of loop
Better:
let html = ''; // Global Scope
for (let i = 0; i < pets.length; i++) {
let pet = pets[i];
html += `
<h2>${pet.name}</h2>
<h3>${pet.type} | ${pet.breed}</h3>
<p>${pet.age}</p>
<img src="${pet.photo}" alt="${pet.breed}">
`;
} // End of loop
document.querySelector('main').insertAdjacentHTML('beforeend', html);
Peter Lord
10,034 PointsPeter Lord
10,034 PointsHeya -- we declare the html variable multiple times through the exercise, at the beginning, in the loop, and the end.
We declare the variable at the beginning as a starting point, then we loop over the variable (6 times while adding all the pet information) and then we use it one last time to insert the results to the html document
***Tiny note that my solve wasn't how the instructor did it, I declared the variables within the loop..