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 trialamin mbarki
2,110 Pointswhat's wrong with this code
var html = '';
var red;
var green;
var blue;
var rgbColor;
function randomColor() {
return math.floor(math.random() * 256 );
}
for (i = 0 ; i < 10 ; i += 1) {
red = randomColor();
green = randomColor();
blue = randomColor();
rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
html += '<div style="background-color:' + rgbColor + '"></div>';
document.write(html);
}
my first problem is the function won't work and i didn't get the error in the console second the 'document.write' when i ran it inside the loop the loop ran more than 10 time so it gave me more than 10 circles but outside the loop it works could you guys explain to me why . thanks for helping a lot
1 Answer
Steven Parker
231,269 PointsThe misspelling of "Math" (as "math" with lower-case "m") is the reason the function isn't working.
And you see more elements than you were expecting because the concatenation assignment operator ("+=") causes the "html" variable to be added to instead of replaced. So each time through the loop, all the previous elements are reprinted along with one new one. To fix it, just change the operator to a normal assignment ("=").