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

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.