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

arik
arik
5,791 Points

Why do I get black and white shades only after I simplified the red, green, blue variable into just one single variable?

First I simply used all the red, green, blue variable and use this program:

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

for( var x = 0; x < 10; x ++ ){

red = Math.floor(Math.random() * 256 );

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

document.write(html);

That works fine, and then I simplified the red, green, blue variable into one single color variable- since I thought they're the same function. But then I got only black and white color shades. Can anyone please help to explain this?...

var html = ''; var color; var rgbColor;

for( var x = 0; x < 10; x ++ ){ color = Math.floor(Math.random() * 256 ); rgbColor = 'rgb(' + color + ',' + color + ',' + color + ')'; html += '<div style="background-color:' + rgbColor + '"></div>'; } document.write(html);

1 Answer

andren
andren
28,558 Points

The first solution generates a unique number for the red, green and blue values. The second solution generates one random number that all of them are set to. So the first code will generate values like this:

rgb(125, 53, 63)
rgb(215, 111, 104)
rgb(2, 14, 200)

While the second code will produce values like this:

rgb(125, 125, 125)
rgb(14, 14, 14)
rgb(212, 212, 212)

Colors that have the same amount of red, green and blue tend to be pretty colorless.

arik
arik
5,791 Points

First of all sorry for the typo in the first code, rgbColor = 'rgb(' + color + ',' + color + ',' + color + ')'; those color should be red, green, and blue.

Thank you for the answer, I get the point:)