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

Shorter code with only one variable (var html) - good practice?

I have eliminated all but var html and instead of using variables in the functions and the for loop, I've directly inserted the functions that I've declared beforehand. Question: Is my solution common practice, or is it better to use variables and a few more steps? Thanks for your input! My code looks like this:

var html = '';

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

function randomRGB() {
  return 'rgb(' + randomColor() + ',' + randomColor() + ',' + randomColor() + ')';
}

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

document.write(html);
Dave StSomeWhere
Dave StSomeWhere
19,870 Points

For inserting function() names instead of variables - I think it is quite common and also makes you think about using a useful/meaningful name. Is randomColor() a good name for a value between 0 and 255?

Hi Dave StSomeWhere, good point, I'll rethink the naming!

Thank you Piotr Manczak!

1 Answer

Steven Parker
Steven Parker
231,236 Points

Keeping your code concise is a very good practice except in rare cases where it impedes readability.

More often it will improve readability and efficiency, as I believe you have done here.   Good job! :+1:

Thanks for your feedback, Steven Parker!