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

Joshua Thorley
Joshua Thorley
7,886 Points

Why does 'undefined' display in my document?

I've condensed or "refactored" the .js file in numerous ways and keep stumbling across the same discrepancy. All ten divs display in varying colours as expected, however the document displays "undefined" before the circular divs.

Here is one of my solutions that causes the issue (any refactoring feedback would also be welcomed):

var html;

for (var divCounter = 0; divCounter < 10; divCounter += 1) {
  var red = Math.floor(Math.random() * 256 );
  var green = Math.floor(Math.random() * 256 );
  var blue = Math.floor(Math.random() * 256 );
  var rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
  html += '<div style="background-color:' + rgbColor + '"></div>';
}

document.write(html);

Thanks guys

Deleted your double post

2 Answers

Simon Coates
Simon Coates
28,694 Points

you might want to start var html = ""; The problem is the use of += on an undefined variable.

Joshua Thorley
Joshua Thorley
7,886 Points

Thanks Simon. Something I'm not sure about having just re-read the code - is it ok do define the variables within the loop itself? Does this mean the variables are being redeclared every time the code is executed or is it ok?

Simon Coates
Simon Coates
28,694 Points

it's fine. it runs var divCounter = 0 just once, at the beginning.