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 Solution

keren lerner
keren lerner
3,561 Points

I used a function and it works. Is this wrong?

var html = '';
var red;
var green;
var blue;
var rgbColor;


function colorFunction () {

red = Math.floor(Math.random() * 256 );
green = Math.floor(Math.random() * 256 );
blue = Math.floor(Math.random() * 256 );
rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
html += '<div style="background-color:' + rgbColor + '"></div>';

document.write(html);  


}

colorFunction ();

//Fixed Code Presentation

How to post Code

keren lerner
keren lerner
3,561 Points

Thanks, that's good to know!

1 Answer

Gunhoo Yoon
Gunhoo Yoon
5,027 Points

If your code works as your intention it's not wrong.

What your function will write on web page is plain text that will look like this.

rgb(50, 48, 75)

If that's what you intended that's perfect except you can clear few things out.

function colorFunction() {
  //Notice how you can declare multiple variable with single var.
  var red = Math.floor(Math.random() * 256 ),
        green = Math.floor(Math.random() * 256 ),
        blue = Math.floor(Math.random() * 256 );

  document.write('rgb(' + red + ',' + green + ',' + blue + ')');
}

Here is reason why I removed few of your variables which seemed unnecessary to me.

  1. variables outside of function is not needed since you are not using it after function is called.

  2. variable rgbColor and html does duplicated things at the end. (they hold rgb(12, 43, 17) string).

  3. Apparently, the string you created is only used inside the function. Then this can be omitted as well, just pass the string directly to document.write

Feel free to comment for more curiosity.