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

Could it be a solution with an array or is it unnecessary?

var html = '';
var rgbColors = new Array();
var rgbColor;

for (var i=0; i<10; i+=1){
  rgbColor='rgb(';   

  for(var x=0; x<3; x+=1){
  rgbColors[x] = Math.floor(Math.random() * 256 );
  rgbColor+=rgbColors[x];

  if( x<2){
  rgbColor+=',';
  }
    else{
    rgbColor+=')';
    }
   }
  html += '<div style="background-color: ' + rgbColor + ' "></div>';
}

document.write(html);

1 Answer

Hi Adam. You could definitely use an array if you wanted, but in this case I'd say something simple would be better, if not only for the sake of readability.

var html = '';
var r, g, b;
var rgbColor;

for (var i=0; i<10; i+=1){
  r = Math.floor(Math.random() * 256 );
  g = Math.floor(Math.random() * 256 );
  b = Math.floor(Math.random() * 256 );

  rgbColor = 'rgb(' + r + ',' + g ',' + b + ')';

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

document.write(html);

When someone looks at this code, maybe even your future self, it'll be immediately understandable. It may even run faster too, since there are less conditions, though performance is not even an issue here. As an added bonus, now each random color range is easily modifiable compared to the array method. Sometimes clever tricks and further automation will only hurt your code as it gets larger and older. You'll have to figure out which is better for each situation.

Thank you, you're right. Even it was more time to make the code than its easier version :).