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

Doesn't the code in the solution in this video seem a little long winded?

Here is my solution (open to criticism):

var html = '';
var rgbColor;

//Function

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

//Loop

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

document.write(html);

3 Answers

Michael Williams
PLUS
Michael Williams
Courses Plus Student 8,059 Points

In what sense? Are you looking for a way to simplify it?

You could use jquery to make the loop but I believe you would need to create 10 div tags in your html to go that route, in addition to loading jquery. So in that event, the code would about equal out?

Thanks for the reply! I couldn't help but notice that in the solution in the video, there were significantly more lines of code than in mine. My code seems to work fine, but it kind of made me scratch my head. I know there are many possible solutions to this challenge, but the fact that mine was shorter made me wonder if, me being new, there are disadvantages to the brevity of my code that I am unable to see? In other words, I'm wondering if his solution has more code for a reason, and if my code being so much more compact is too good to be true, so to speak.

Michael Williams
PLUS
Michael Williams
Courses Plus Student 8,059 Points

Yeah, I'm still learning too. So feel free to call me out if my answer is off. My guess is that they're just showing the foundation of how to write the code to firm up the concepts. From there, you can learn the fancier, shorter code.

Joel Stevenson
Joel Stevenson
4,137 Points

Yeah, I felt the same way. Here was mine...

function newColor(color) { color = Math.floor(Math.random() * 256 );
return color; } for (i=0; i <= 10; i+= 1) { var html = ''; var rgbColor; rgbColor = 'rgb(' + newColor(color) + ',' + newColor(color) + ',' + newColor(color) + ')'; html += '<div style="background-color:' + rgbColor + '"></div>'; document.write(html) }

I'm still learning too, open to critique