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

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
216,121 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
216,121 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
216,121 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.