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 trialSundeep Singh
1,565 PointsHeIp please! I am really not understanding why document.write is not inside the loop .
for(var i = 0; i < 10; i++) {
red = randomRgb( );
green = randomRgb( );
blue = randomRgb( );
rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
html += '<div style="background-color:' + rgbColor + '"></div>';
}
document.write(html);
like is see in this example
for(count = 0; count < 10; count++){
document.write("Current Count : " + count );
document.write("<br />");
}
2 Answers
Shawn Boyd
14,345 PointsIn the lower example you posted, the loop and document.write are working together to print a message for each iteration of the loop - writing as the loop progresses.
In the first, however, the loop is being used as a quick way to build up a chunk of html before writing that entire chunk to the document at once. Were the document.write to be included in that loop it would print the entire collection of divs at the end of each loop:
when i=0, writes the first div
when i=1, writes first div again and then the second
when i=2, writes first and second divs again and then the third
and so on...
This isn't what you want if you're concatenating a new div with every iteration of the loop.
You could include the document.write(html) within the loop by changing the "html += ..." to "html=..." but then you're running 10 write commands, rather than just one by keeping it outside of the loop.
Anthony Trischitti
12,259 PointsYes, It is essentially continuing to add to the string each time the loops runs with the += sign