Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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