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 trialsorin vasiliu
6,228 Pointsrefactor challenge quickie quick question
Hey guy! Why do I have to make i < 4 in order to print out 10 colors ? what did I do wrong in the code ?
var html = '';
var red;
var green;
var blue;
var rgbColor;
function randomColor() {
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 < 4; i++ ) {
randomColor();
}
As a result, this prints out 10 color bubbles. Why? I don't get why it adds up to 10... Thanks!
1 Answer
Daniel Newman
Courses Plus Student 10,715 PointsWhat you do is "factorial". Look:
function randomColor() {
html += '<div style="background-color:' + rgbColor + '"></div>';
document.write(html);
}
for ( var i = 0; i < 4; i++ ) {
randomColor();
}
Your html for times (html = html + newone): yourloop { html = html + newone; }
It will be
html = html + newone
html = ( html + newone ) + newone
html = ( html + newone + newone ) + newone
html = ( html + newone + newone + newone ) + newone
html = ( html + newone + newone + newone + newone ) + newone
You can put console.log(html) inside your loop to see how it happens.
sorin vasiliu
6,228 Pointssorin vasiliu
6,228 PointsYup! I see it now! Thank you for the good inside!