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 Loops, Arrays and Objects Simplify Repetitive Tasks with Loops The Refactor Challenge Solution

I put document.write(html) inside my for loop

Here is my solution. https://w.trhou.se/e7wwgfbezt

Kristaps Vecvagars
Kristaps Vecvagars
6,193 Points

Technically your code works, the result is the same, and you did nothing wrong, but... Putting document.write inside the loop means that every time a single lap of the loop runs, something is written in your html, and that can potentially slow down your program. Putting document.write outside the loop means that the program only writes to the page once, when the entire string is complete. In my opinion it's a more optimal approach.

Think of it this way - if you need 10 bottles of water, you can go to the store 10 times and bring back a bottle each time, but wouldn't it be more rational to go to the store once, stuff all 10 bottles in a bag and bring all 10 of them back at once?

1 Answer

Actually putting document.write() inside the loop would result in a sum of the sequence of divs created each time through the loop, so if you ran through the loop 10 times you would get 55 dots displayed (n*(n+1)/2) where n=10. This is why the document.write() code needs to be outside of the loop.