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

Tom Dakan
Tom Dakan
3,967 Points

Funny way to Refactor

Please note, I don't consider this a good solution, just a funny one. I'm really getting my money's worth from those loops.

var html = '';
var color;
var rgbColor;

for (j=0;j<10;j++){
  rgbColor = 'rgb(';
  for (i=0;i<3;i++){
    color = Math.floor(Math.random() * 256 );
    rgbColor +=color;
    if (i < 2) rgbColor +=',';
  }
  rgbColor += ')';
  console.log(rgbColor);
  html += '<div style="background-color:' + rgbColor + '"></div>';
}

document.write(html);

3 Answers

Tom Dakan
Tom Dakan
3,967 Points

I consider it 'not good' because there are much more readable ways to do the same thing (extracting the logic into another function or two with good naming.) The string concatenation is also a little dicey since I'm adding the beginning and ending parentheses outside of the inner loop. The creation of the rgb() function string is totally dependent on the outer loop running correctly.

Performance-wise I suspect it's probably comparable, and in that sense, a valid solution.

Steven Parker
Steven Parker
231,269 Points

Having one part of a program "totally dependent on another part running correctly" is a common and inevitable aspect of programming.

Steven Parker
Steven Parker
231,269 Points

Good point about readability, but in this case the code is small enough that I wouldn't consider that a significant issue.

Steven Parker
Steven Parker
231,269 Points

I like it. :+1:

I think I would call it a good solution. Maybe not the best possible, but good.

Creative Yes! But as Tom Daken put it, it should be readable, and maintainable by anyone other than the author. Short, clear, concise.