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

document.write(), inside block or outside

What is the difference between putting document.write() inside code block or outside of it?

I noticed it is actually wrong between the codes I wroted. But I don't get why this is happening.

var html = '';
var red;
var green;
var blue;
var rgbColor;
var count = 1;

while (count <= 10){
    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>';
    count += 1;
}

document.write(html);
var html = '';
var red;
var green;
var blue;
var rgbColor;
var count = 1;

while (count <= 10){
    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>';
    count += 1;
    document.write(html);
}

1 Answer

Ryan Markey
seal-mask
.a{fill-rule:evenodd;}techdegree
Ryan Markey
Front End Web Development Techdegree Student 12,565 Points
while (count <= 10){
     document.write(html);
}

This will write the 'html' variable to the page 10 times.

while (count <= 10){

}
document.write(html);

This will only do it once.

while (count <= 10){
    html += '<div style="background-color:' + rgbColor + '"></div>'; 
}
document.write(html);

Because you are using '+=' on the 'html' variable each pass through the 'while' loop adds a new <div> to the variable so calling 'document.write(html);' once is enough.

You code works fine in CodePen.

I used the following CSS to style the <div>:

div {
  margin-left: 15px;
  display: inline-block;
  height: 4rem;
  width: 4rem;
  border-radius: 50%;
}