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, Part 2

Can I place variable html and function print inside the loop while ?

Can I place variable html and function print inside the loop while ?

function random1Color() { return Math.floor(Math.random() * 256 ); }

function print(message) { document.write(message); }

function rgbColor() { var colors = 'rgb(' + random1Color() + ',' + random1Color() + ',' + random1Color() + ')'; return colors; }

var counter = 0;

while ( counter < 10 ) { var html = ''; html += '<div style="background-color:' + rgbColor() + '"></div>'; counter += 1; print(html); }

2 Answers

Steven Parker
Steven Parker
210,423 Points

The loop keeps adding elements to "html". So if you print inside the loop, instead of just 10 elements you'll get the sum of 1 + 2 + 3 ... all the way to 10 — which will be 45 elements! And with many of the same colors repeated.

Steven Parker
Steven Parker
210,423 Points

Regarding your revision: you certainly can do that, but you could also just declare and assign the variable in one step:

       var html = '<div style="background-color:' + rgbColor() + '"></div>';
       var html = '<div style="background-color: ${rgbColor()}"></div>';

Either way, the difference is that this method prints out each color by itself inside the loop, but the original method created all 10 in the same string and then printed them one time outside of the loop.

Thank you for your answer. You are right of course. I had a lot of elements before but what if I put a var html = ' '; also inside a loop ? It seems to work correctly. I have 10 different colour elements. Or I should not ?

      while ( counter < 10 )  {

       var html = ' ' ;

       html += '<div style="background-color:' + rgbColor() + '"></div>';

       counter += 1; 

       print(html); 
 }
Steven Parker
Steven Parker
210,423 Points

See the comment I added to my answer.