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, 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
231,236 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
231,236 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.