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
173,943 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
173,943 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.