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 trialkeren lerner
3,561 PointsI 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 ();
keren lerner
3,561 PointsThanks, that's good to know!
1 Answer
Gunhoo Yoon
5,027 PointsIf 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.
variables outside of function is not needed since you are not using it after function is called.
variable rgbColor and html does duplicated things at the end. (they hold rgb(12, 43, 17) string).
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.
Chyno Deluxe
16,936 PointsChyno Deluxe
16,936 Points//Fixed Code Presentation
How to post Code