## Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

### Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today. # Why there is a difference between putting the document.write inside the for loop and outside the for loop

A. var html = ''; var red; var green; var blue; var rgbColor; for(var i = 0; i < 10; i+=1){ red = Math.floor(Math.random() * 256 ); green = Math.floor(Math.random() * 256 ); blue = Math.floor(Math.random() * 256 ); rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')'; html += '<div style="background-color:' + rgbColor + '"></div>';

} document.write(html);

B. var html = ''; var red; var green; var blue; var rgbColor; for(var i = 0; i < 10; i+=1){ red = Math.floor(Math.random() * 256 ); green = Math.floor(Math.random() * 256 ); blue = Math.floor(Math.random() * 256 ); rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')'; html += '<div style="background-color:' + rgbColor + '"></div>'; document.write(html); }

I worked on the challenge in the video with the code above and I find the number of color dots is difference. With the code in A above, I find the number of color dots is 10 in the end whereas the code in B above will lead to more than 10 color dots. Could anyone please explain why? Thank you!

Why there is a difference between putting the document.write inside the for loop and outside the for loop

if you put a statement inside of any loop, it is going to run with each iteration of the loop.

If you put it outside of the loop, it is going to run once In the first example. the loop keeps adding new elements to the "HTML" string, then "document.write" is called to place all 10 on the page at once.

In the second example, as the "HTML" string is being made, the contents are being written to the page every time. So all the ones previously written are witten again, plus a new one. By the time the loop finishes, the first one will have been written 10 times, the second one 9 times, the third 8, and so on. There should be a total of 55 items (but only 10 unique ones).

What's happening might be more obvious if you include the index value inside each element:

```  html += '<div style="background-color:' + rgbColor + '">' + i + '</div>';
```

you should remove the plus sign next to (html)

`html = '<div style="background-color:' + rgbColor + '">' + i + '</div>';`