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

Rachael Benedict
Rachael Benedict
7,242 Points

Refactor Challenge - please critique my code.

Please could someone critique my code for best practice and point out any errors. I haven't managed to use D.R.Y on the part that creates the random numbers within the function so any ideas on how to do this would be great.

Thank you in advance.

// TO CREATE 10 RANDOMLY COLOURED DIVS

var html = '';

function colouredBalls() { var red = Math.floor(Math.random() * 256 ); var green = Math.floor(Math.random() * 256 ); var blue = Math.floor(Math.random() * 256 ); var rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')'; html = '<div style="background-color:' + rgbColor + '"></div>';

return html;

}

for(i = 1; i <= 10; i += 1) { document.write(colouredBalls()); }

2 Answers

The part that generates the random RBG color is repeated. [ Math.floor(Math.random() * 256 ); ]

It's also recommended to print the result once to the user, not using a loop.

Here is the code I developed for that challenge:

var html = '';

function rColor() { return Math.floor(Math.random() * 256 ); }

function rgbColor() { return 'rgb(' + rColor() + ',' + rColor() + ',' + rColor() + ')' };

function print(text){document.write(text);}

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

print(html);
Rachael Benedict
Rachael Benedict
7,242 Points

Thank you for that. It's very helpful. How do you print your code in colour like that please?

You're welcome. For the code-box check the Markdown Cheatsheet under the comment area.