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

Cameron O'Brien
Cameron O'Brien
11,564 Points

Is this ok for a solution?

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

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

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

document.write(html);

Thanks for the input, any help is appreciated. Have a good day.

1 Answer

Shane Oliver
Shane Oliver
19,977 Points

The only global variable you need in this case is the html variable. The rest are only temporary, and you can get by without them. It might also be cleaner and more readable to extract another function to handle create the rgb color

Here is my solution

let html = '';

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

function getRGBColor() {
    return `rgb(${randomColor()},${randomColor()},${randomColor()})`;
}

for(var i = 0; i < 10; i++) {
    html += `<div style="background-color: ${getRGBColor()};"`;
}

document.write(html);