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

What if I do it like this???

is there any prob in this?

function randomNum(){
return Math.floor(Math.random() * 256 );
}

function randomColor(){
var red = randomNum();
var green = randomNum();
var blue = randomNum();
return rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
}

for( i = 0; i < 10; i += 1){
document.write('<div style="background-color:' + randomColor() + '"></div>');
}

5 Answers

That looks and works great! Only comment could be that "return rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')'; " could be reduced to "return 'rgb(' + red + ',' + green + ',' + blue + ')'; "

While adding the rgbColor variable helps clarify what the return value is, what you are actually doing in this line is storing the rgb function call in a global variable that is never used, which is not ideal.

Thanks in advance

Oh, Thank you for your time and effort... You're right, I was looking for improvisation and look what I came up with:

function randomNum(){
return Math.floor(Math.random() * 256 );
}
function rgbValue(){
  var color= 'rgb(';
      color += randomNum() + ",";
      color += randomNum() + ",";
      color += randomNum() + ")";
return color;  
}
for (i = 1; i <=1000; i += 1){
document.write('<div style="background-color:' + rgbValue() + '"></div>');
}

Though this one is much more complex, it is far more efficient and compact. I like this one better, don't you think?

Manuel Aviles
Manuel Aviles
4,995 Points

So would this be the only block of code you write or would you have to write that 10 more times since there was 10 blocks of code?

Hey Manuel Aviles, why would I repeat that block of code when I've already set the counter in for loop to do the job for me? In fact the latter one that I've posted can produce a 1000 color balls... I've set the upper limit to 1000, if you see then you'll understand it.