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

sorin vasiliu
sorin vasiliu
6,228 Points

refactor 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

What 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
sorin vasiliu
6,228 Points

Yup! I see it now! Thank you for the good inside!