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

Christine Bogdan
Christine Bogdan
5,299 Points

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,783 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?

1 Answer

Steven Parker
Steven Parker
173,904 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: