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

Tried using a function and a loop but its there are too many div elements.

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

function color(){

red = Math.floor(Math.random() * 256 ); green = Math.floor(Math.random() * 256 ); blue = Math.floor(Math.random() * 256 ); rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')'; html += '<div style="background-color:' + rgbColor + '"></div>'; document.write(html);
}

for ( var i=0; i<10; i++){ color();

}

I get quite a few more divs than 10 even though im using a for loop to execute the function 10 times.

1 Answer

Joel Bardsley
Joel Bardsley
31,249 Points

The html variable isn't being reset each time you run the color() function. The first time color() runs, the html variable is updated with the string containing the first div. The next time the function runs another div gets added to the html variable.

With that in mind, you can see how you're ending up with many more than the 10 divs you're anticipating from executing your for loop.

Seems so obvious now. Thanks!