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, 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
231,275 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
231,275 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
231,275 Points

See the comment I added to my answer.