JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops The Refactor Challenge, Part 2

Mohammed Zeeshan
Mohammed Zeeshan
Full Stack JavaScript Techdegree Student 3,299 Points

My version did work well, but do anyone have thoughts to refactor this code further?

var html = '';
var rgbColor;

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

for(i=1; i<=1000; i++) {
rgbColor = 'rgb(' + color() + ',' + color() + ',' + color() + ')';
html += '<div style="background-color:' + rgbColor + '"></div>';
}

document.write(html);

I have to use color() thrice in a statement, that looks little weird for me

Chris Sukovich
Chris Sukovich
2,261 Points

Hey Mohammed,

This looks great! I did something similar because I wanted to clean up the code from the example a bit further. I iterated the random number loop 3 times, and pushed each result into an array, then joined and comma-separated the values in the array using the .join() method. Check out my code below:

for ( j = 0; j < 10; j++ ) {

  var values = [];
  for ( i = 0; i < 3; i++ ) {
    values.push(Math.floor(Math.random() * 256 ));
  }

  rgb = values.join(',');

  document.write('<div style="background-color: rgb(' + rgb + ')"></div>');
}

3 Answers

Moira Lawrie-Martyn
Moira Lawrie-Martyn
6,673 Points

Here's the version I went with:

var html = '';

var colour = () => Math.floor(Math.random() * 256);

for(var i = 0; i < 16; i += 1)
{
    html += '<div style="background-color:' + 'rgb(' + colour() + ',' + colour() + ',' + colour() + ')' + '"></div>';
}

document.write(html);

This was using the arrow operator as well. Down to 10 lines :)

Junet Ismail
Junet Ismail
3,563 Points

Chris, I was thinking along the same lines however i was unaware of the join and push functions though i did the loops the same as yours.Very clever indeed.. You could probably take it a step further. Though the code wouldn't be as clean but would cut it down by one more extra line is to inject the array join function into document.write function thus getting rid of the RGB variable entirely. As such:-

for ( j = 0; j < 10; j++ ) {
var values = []; for ( i = 0; i < 3; i++ ) { values.push(Math.floor(Math.random() * 256 )); }

document.write('<div style="background-color: rgb(' + values.join(',') + ')"></div>'); }