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 trialGal Parselany
Full Stack JavaScript Techdegree Graduate 26,281 PointsMy solution is good aswell? I dont use the let before the for loops, but only inside the for loops. is that ok?
let html = '';
for (i = 1; i <= 10; i++) {
let red = Math.floor(Math.random() * 256);
let green = Math.floor(Math.random() * 256);
let blue = Math.floor(Math.random() * 256);
let randomRGB = `rgb( ${red}, ${green}, ${blue} )`;
html += `<div style="background-color: ${randomRGB}">${i}</div>`;
}
document.querySelector('main').innerHTML = html;
is that ok too? cause I see that Guil is still using the vars outside the for loops, and I dont understand if its necessary. thanks in advance
1 Answer
Steven Parker
231,269 PointsBy declaring the variables outside the loop, Guil's code inside the loop becomes a simple assignment making the loop more efficient.
Declaring the variables inside the loop will do the same job, but they will be disposed and then re-created for each iteration, using a bit more processor time. But since the loop is simple and short, the difference won't be noticed.