JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops The Refactor Challenge, Part 2

Daniel Sarmiento
Daniel Sarmiento
9,795 Points

I'm getting an "undefined" error when I preview. Please Can you point out the error?

This is what I coded in my Js file:

var times = 10;

/* Gets a random color */
function getColor() {
   return Math.floor(Math.random() * 256 );
}


/* Puts together a random RGB color */
function RandomRGB() {
  var RGB;
  var rgbColors = 3;
  for (var i = 0; i < rgbColors; i++) {
    if ( i === (rgbColors - 1)) {  
      RGB += getColor() + " ";
      break;
    }
    RGB += getColor() + ' ,'; 
  }
  return RGB;
}


/* Puts together a number of RGB colors each one inside a div ready to be
printed out */
function RGBcolors(manyRGBs) {
  var html;
  for (var i = 0; i < manyRGBs; i++) {
    html += "<div style: \"background-color: rgb(" + RandomRGB() + ")>" + "</div>";
  }
  return html;
}


document.write(RGBcolors(times));

2 Answers

james south
james south
Front End Web Development Techdegree Graduate 33,246 Points

the undefined comes from not initializing the html variable to the empty string. also the style tag needs to be followed by an equal = not a colon : and you were missing a quote " mark. finally, the divs need a size in order to appear, so in a css file i added a height and width. so here is my js:

var times = 10;

/* Gets a random color */
function getColor() {
   return Math.floor(Math.random() * 256 );
}

/* Puts together a number of RGB colors each one inside a div ready to be printed out */

function RGBcolors(manyRGBs) {
  var html = "";
  for (var i = 0; i < manyRGBs; i++) {
    html += "<div style=\"background-color: rgb(" + getColor() +","+getColor()+","+getColor()+ ")\"></div>";
  }
  return html;
}

document.write(RGBcolors(times));
Daniel Sarmiento
Daniel Sarmiento
9,795 Points

Thank you!

and also

How can I implement a function that stores the 3 RGB colors so that I don't need to call "getColor()" three times? Any hints?

Thanks again!

james south
james south
Front End Web Development Techdegree Graduate 33,246 Points

you could do something like this:

function colors(){
    var cols = "";
    for (var i = 0; i < 3; i++){
        cols += getColor() + ",";
    }
    return cols.substring(0,cols.length-1);
}

and then call it like:

function RGBcolors(manyRGBs) {
  var html = "";
  for (var i = 0; i < manyRGBs; i++) {
    html += "<div style=\"background-color: rgb(" + colors() + ")\"></div>";
  }
  return html;
}