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

Sam Weeks
seal-mask
.a{fill-rule:evenodd;}techdegree
Sam Weeks
Front End Web Development Techdegree Student 16,699 Points

can any one explain?

solved the challenge but given the code below im confused as to why it is producing 10 coloured circles rather than 4

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



 for (var i = 0 ; i <= 3 ; i += 1) { 
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);
}

1 Answer

JEFF CHAI
JEFF CHAI
7,564 Points

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

The above statement with make 10 div in your page. You using += it will at add the previous string in the next loop.So when you running your for loop

Loop Count and Div add in html

  0                                 1
  1                                 2
  2                                 3
  3                                 4

Therefore, after the exit the for loop you will have 1+2+3+4=10 div in your html Just simply remove the + and can produce the result what you want.

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

Sam Weeks
seal-mask
.a{fill-rule:evenodd;}techdegree
Sam Weeks
Front End Web Development Techdegree Student 16,699 Points

i think i can kind of grasp what your saying. JavaScript so far has produced alot of aha moments "I get it now" whilst equally producing a lot of hair pulling moments . for instance i can put the document.write outside of the curly braces and change the <= to 10 and it works that way as well.

cheers Jeff