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

Does this still work too???

I got it right, but I used a simpler way to get the answer. Could someone please tell me if the way I did it is sufficient or not???? Thanks in advance!

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

for (var i = 0; i <= 10; i += 1) { allColors = red, green, blue, rgbColor, html; allColors = Math.floor(Math.random() * 256); } document.write(html);

2 Answers

Hi Hunter

The code you have put doesn't give the same results

within your, for loop, you just assign allColors to all the variables and then assign allColors to the Math.floor

However, it looks like your trying to prevent repeating yourself with the Math.floor, there's a bunch of ways of doing this, you can use arrays, objects, etc

Heres how I would follow DRY coding for the random generation

var html = '',
    rgbColor,
    allColors = {red: "", green: "", blue: ""};

for (var i = 0; i <= 10; i += 1) {
    for (colors in allColors) {
        allColors[colors] = Math.floor(Math.random() * 256);
    }
    rgbColor = `rgb(${allColors.red}, ${allColors.green}, ${allColors.blue})`;
    html += `<div style="background-color: ${rgbColor};"></div>`;
}
document.write(html);

Hope this helps

It doesn't work. Run this through the console and see what you get.

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

for (var i = 0; i <= 10; i += 1) {
    allColors = red, green, blue, rgbColor, html;
    console.log(allColors)
    allColors = Math.floor(Math.random() * 256);
    console.log(allColors)
}

console.log("HTML = " + html) 
document.write(html);