JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops The Refactor Challenge, Part 2

Jesse Vorvick
Jesse Vorvick
Full Stack JavaScript Techdegree Student 4,459 Points

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
PRO
Michael Williams
Pro Student 8,057 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?

Jesse Vorvick
Jesse Vorvick
Full Stack JavaScript Techdegree Student 4,459 Points

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
PRO
Michael Williams
Pro Student 8,057 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,136 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