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

Josh Arrington
PLUS
Josh Arrington
Courses Plus Student 2,796 Points

Why is the document.write() function outside of the loop?

I'm curious as to why the document.write() function is written once outside of the loop.

To me it would make sense that each time the color is generated and assigned to the html variable in the loop, it's written to the screen. That happens 10 times and the loop is over. This seems to work when I move the document.write() function as the last line of the loop.

But why does it work with the document.write() function outside of the loop and written only once?

3 Answers

Robert Manolis
STAFF
Robert Manolis
Treehouse Guest Teacher

First, love your profile pic. Roger is the greatest.

If the document.write was inside the loop, then everything would be written to the page once for each iteration of the loop. You'd end up with a bunch of duplicates.

Putting it outside the loop means it only writes once.

vanessa
vanessa
3,455 Points

Either way it would work, it just a matter of preference.

if it is inside the loop, then it writes every time the loop runs. if it is outside the loop, then it collects the data first. Like it saves the data inside a variable first. then prints it all one time.

Josh Arrington
PLUS
Josh Arrington
Courses Plus Student 2,796 Points

Thanks, that actually helped me clear it up. I didn't notice the concatenation of the 'html' variable so I thought it was being overwritten with every iteration. That makes a lot more sense!

Robert Manolis
Robert Manolis
Treehouse Guest Teacher

Don't forget to mark best answer if there is one or give an up vote for answers you think are good. :)