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

Jeffrey Huang
Jeffrey Huang
5,914 Points

Alternative? For-loop inside a for-loop

Hi I was wondering why this code doesn't.

var html = ''; var rgbColor = 'rgb(';

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

for (var i=0; i<10; i++) { for (var j=0; j<3; j++) { j = colorNumber(); rgbColor += j if (j < 2) { rgbColor += ','; } else { rgbColor += ')'; } } html += '<div style="background-color:' + rgbColor + '"></div>'; }

document.write(html);

There was also a mention of alternative solutions. Is anyone able to show them?

(Sorry it's not set out properly. I couldn;t find any button that lets me attach code through treehouse so I had to copy and paste)

1 Answer

Corina Meyer
Corina Meyer
9,990 Points

First, why your code might not work as expected:

  • the rgbColor variable should be declared inside the outer for loop
  • the counter variable (j) is also used to get a colorNumber, this overwrites the counter

Another possibility to write this without two for-loops

var html = '',
    rows = 10;

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

function rndColor() {
  var rgb = [colorNumber(), colorNumber(), colorNumber()];
  return 'rgb(' + rgb.join(', ') + ')';
}

for(var c = 0; c < rows; c++) {
  html += '<div style="background-color: ' + rndColor() + '"></div>';
}

document.write(html);

and if you want to learn about markdown (the treehouse markdown cheatsheet seams to no longer be available), you could google for "markdown cheatsheet". i would link one here, but i don't think that would be allowed?

Jeffrey Huang
Jeffrey Huang
5,914 Points

Ahh okay that makes sense. I guess I'd have to apply javascript to be learnt in further sessions to be able to complete it in other alternative methods.

Thank you!