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

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>';

Dave StSomeWhere
Dave StSomeWhere
19,822 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
217,602 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!