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

Mohd Aamir Mir
Mohd Aamir Mir
3,281 Points

why do we write the document.write statement outside the loop?

Why cant we use the document.write statement inside the loop? whats the reason it is shown outside the 'for' loop in the video?

2 Answers

Dmitry Polyakov
Dmitry Polyakov
4,989 Points

For loop and document.write play two different roles. For loop builds your html. document.write takes the value of html and prints it to a document. There is no need to put them together. This way you get a much cleaner and easily understandable code.

Kristaps Vecvagars
Kristaps Vecvagars
6,193 Points

I believe putting document.write inside the loop can slow down your program, especially, if you'd want to generate a huge number of elements. In this particular case it probably doesn't matter, but you should build the entire string first and only write it to the document once not every time it's changed.

Think of it as going to the store 10 times in a row to get 10 items. Wouldn't it be more rational to go to the store only once, stay there awhile to get the 10 items you need, and go back home only once?

Mohd Aamir Mir
Mohd Aamir Mir
3,281 Points

@ Kristaps Vecvagars thanks for such a beautiful explanation.I already got this :)

Since the html+= code is appending the value of html each time through the loop then including the document.write(html) inside the for loop writes the value of html each time through the loop, resulting in a sum of the sequence of divs, ie n*(n+1)/2. So 10 times through the loop gives me 55 divs instead of the desired 10. So putting the document.write(html) outside the for loop is required unless you want to end up with a sum of the sequence of divs...