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, Part 2

My solution was this

Here is my code could be better but was similar to the instructor. :)

var html = '';

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

for (var i = 0; i <= 100; i +=1 ) {
rgbColor = 'rgb(';
rgbColor += random256 () + ',';
rgbColor += random256 () + ',';
rgbColor += random256 () + ')';
html += '<div style="background-color:' + rgbColor + '"></div>';
   }
document.write(html);

but in this example is way faster this way. ( i know we are learning the concepts)

var html = '';
for (var i = 1; i <= 100; i += 1) { 
red = Math.floor(Math.random() * 256 );
green = Math.floor(Math.random() * 256 );
blue = Math.floor(Math.random() * 256 );
rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
html += '<div style="background-color:' + rgbColor + '"></div>';
}
document.write(html);

2 Answers

Steven Parker
Steven Parker
210,487 Points

It is a bit faster, but at the cost of violating the "DRY" principles and using repeated code.

On the other hand, this is even faster, and still observes the "DRY" principles:

var html = '';
var rc = () => Math.floor(Math.random() * 256);
for (var i = 1; i <= 100; i++) {
    html += '<div style="background-color:' +
       'rgb(' + rc() + ',' + rc() + ',' + rc() + ')' + '"></div>';
}
document.write(html);

Hey i try that and didn't work for me. now i see why. thanks for your answer. what s the principle of var rc = () => ? I'm not yet in that part of the curse.

i try it normal var rc = Math.floor(Math.random() * 256); , but didn't work so the key was () => i have to lern more about that.

Steven Parker
Steven Parker
210,487 Points

That's an arrow function, it's essentially the same as your "random256" function with a more concise syntax.

Yes i found a good lecture on that function here https://codeburst.io/javascript-arrow-functions-for-beginners-926947fc0cdc

I will check it out thanks.