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

Carlos Lantigua
Carlos Lantigua
5,938 Points

Evaluate my code please

Not sure if it is because of how amazing Dave's teaching is and that I'm taking notes but this challenge only took me about 1 minute to get to this point. Let me know what you guys think and if I could have made this any shorter or better in any way, thanks as always. https://w.trhou.se/joi3f6xxuk

1 Answer

Justin Cantley
Justin Cantley
18,068 Points

Your code looks and works great! But since you asked, I did find a shorter way to write your js.

var html = '';

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

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

document.write(html);

This makes your code DRY (Don't Repeat Yourself). It also eliminate the need to declare extra variables. Most importantly, it has the same result as your original code.

Hope this helps!

Carlos Lantigua
Carlos Lantigua
5,938 Points

thanks a lot, until I watched the vid after this I had no idea you could concatenate rgb() like that, I figured it would break the entire code up or something. Pretty cool to know you can do stuff like that.

Jason Ellsworth
Jason Ellsworth
3,129 Points

really sucks that this spoiled the second part haha