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

Ryan Schmelter
Ryan Schmelter
9,710 Points

I used a function and called it in the for loop. It got weird. Can anyone tell me why?

This code is producing a lot more colors than 10. Just wondering why.

function generateColor() {
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>';
}

for (var i = 0; i <=10; i += 1) {
  generateColor();
  document.write(html);
}

3 Answers

james south
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
james south
Front End Web Development Techdegree Graduate 33,271 Points

in your dev tools look at the colors in the divs created. you see lots of repeating colors. this is because the html string is not being reset to empty, so each successive function call is concatenating a new color onto the string of previous colors. it gets longer and longer with each trip through the loop. find a way to reset the string that creates the colored divs.

Ricardo Ferreira
Ricardo Ferreira
1,466 Points

You only need to create a function to return each color and assign to appropriate variable;

Sean Adamson
Sean Adamson
6,682 Points

The document.write(html) needs to be outside the for loop. Otherwise it keeps concatenating this line:

html += '<div style="background-color:' + rgbColor + '"></div>';

Basically on each loop iteration this is happening to the the html variable,

iteration 1: 1 div = 1 div

iteration 2: 1 div + 2 div = 3 divs

iteration 3: 1 + 2 + 3 = 6 divs

iteration 4: 1 + 2 + 3 + 4 = 10 divs

iteration 5: 1 + 2 + 3 + 4 + 5 = 15 divs

iteration 6: 1 + 2 + 3 + 4 + 5 + 6 = 21 divs

iteration 7: 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28 divs

iteration 8: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36 divs

iteration 9: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45 divs

iteration 10: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55 divs