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.

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops The Refactor Challenge Solution

wataru ando
wataru ando
4,575 Points

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

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%;
}