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 Solution

Luqman Shah
Luqman Shah
3,016 Points

My Solution for the Second Challenge

Is this sufficient?

var html = '';
var red;
var green;
var blue;
var rgbColor;

var getNumber

function getRandomNumber() {
  getNumber = Math.floor(Math.random() * 256 );
  return getNumber;
}

for (var i = 0; i < 100; i += 1) {
  red = getRandomNumber();
  green = getRandomNumber();
  blue = getRandomNumber();
  rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
  html += '<div style="background-color:' + rgbColor + '"></div>';
}

document.write(html);

2 Answers

Steven Parker
Steven Parker
231,269 Points

Did it work for you? For me, nothing shows because the created elements have no vertical dimension (height). But that can be easily fixed by printing out the loop value inside each one:

  html += '<div style="background-color:' + rgbColor + '">' + i + '</div>';
Luqman Shah
Luqman Shah
3,016 Points

Yeah it actually worked for me.

Steven Parker
Steven Parker
231,269 Points

With what browser (I'm using Chrome)?

Luqman Shah
Luqman Shah
3,016 Points

I am also using chrome, here I'll fork it.

Steven Parker
Steven Parker
231,269 Points

Oh, I see! Much different with the CSS! And what you provided was a snapshot, but it allowed me to "fork" it.

Anyway, with that CSS included, your script does the job perfectly as-is. Good job! :+1:

Steven Parker
Steven Parker
231,269 Points

You could take Seamus's suggestion another step and make the code even more compact with an "arrow" function:

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

Looks good.

The only minor change I'd make would be to remove the "getNumber" variable. Instead just return the Math.floor() function inside getRandomNumber().