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, Part 2

Isn't there a way to create a loop so that you don't have to hard code each random color to 'rgb(' ?

Instead of coding color+= randomRGB() + ','; three times couldnt you do something like for (var i=0; i <4; i++) { function randomRGB() { var color = 'rgb('; color += colorPicker + ','; } color += ')';

I'm just not sure how you would return the color though. Just a thought. I'm not sure if this is actually possible.

Erik Nuber
Erik Nuber
20,629 Points

You can turn this...(not quite sure if that was what you were asking)

function getColor(){
  var color = "rgb("; 
  color += randomNumber() + ",";
  color += randomNumber() + ",";
  color += randomNumber() + ")";
  return color
}

into this. Color can be used in both functions because of "scope."

var html = '';
var rgbColor;

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

function moreColor() {
    var color = " ";
 for(var i = 1;  i <= 3; i++){
   if (i <= 2) {
      color += randomNumber() + "," ;} 

  else{
    color += randomNumber() +")";}
  }
  return color;
}

function getColor() {
   var color = "rgb(";
   color += moreColor();
  console.log(color);
   return color;
}


for (var i = 0; i < 10; i += 1) {
  rgbColor = getColor();
  html += '<div style="background-color:' + rgbColor + '"></div>';
}

document.write(html);

I tested it, the only thing is that I think doing it that way makes it more complicated than just calling the functions in a couple of lines.