Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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);