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

Wojciech Samolowicz
Wojciech Samolowicz
6,761 Points

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
186,662 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
186,662 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.

Wojciech Samolowicz
Wojciech Samolowicz
6,761 Points

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
186,662 Points

See the comment I added to my answer.