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

Please, comment and critique my solution for refactoring challenge.

// Variables

var html = '';
var rgbColor;
var hexValue;

// This function generates hex value and returns it

function generateValue() {
  hexValue = Math.floor(Math.random() * 256 );
  return parseInt(hexValue);
}

// The loop generates full rgb value (stores it intro variable) and writes the style for circles 10 times

for ( var i=0; i<10;i+=1 ) {
  rgbColor = 'rgb(' + generateValue() + ',' + generateValue() + ',' + generateValue() + ')';
  html += '<div style="background-color:' + rgbColor + '"></div>';
}

document.write(html);

1 Answer

Well it works very well, good job. However it is unnecessarily verbose in places. For instance; the generateValue() function creates a variable within it, when you could essentially have just written

return Math.floor(Math.random() * 256 );

for the same result. You could also look at adding the code to generate the full RGB values within that one function and then just call that function in your for loop. so it may look something like this:

for ( var i=0; i<10;i+=1 ) {
  rgbColor = generateValue();
  html += '<div style="background-color:' + rgbColor + '"></div>';
}

Noted that! Thank you!