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
Dennis Maurer
2,398 PointsWhy using color += in The Refactor Challenge, Part 2?
i have this two codes:
1: var color = 'rgb(' ; color += randomRGB() + ','; color += randomRGB() + ','; color += randomRGB() + ')'; return color;
and
2: 'rgb(' + red + ',' + green + ',' + blue + ')';
Why i can't write in the first part only:
var color = 'rgb(' ; randomRGB() + ','; randomRGB() + ','; randomRGB() + ')'; return color;
I do only need the rgb colors and the ; in this string...
Thanks, Dennis
1 Answer
Miguel Canas
Python Development Techdegree Student 11,470 PointsHi Dennis,
Regarding this line:
var color = 'rgb(' ; randomRGB() + ','; randomRGB() + ','; randomRGB() + ')'; return color;
The only assignment that occurs is in the initial var color = 'rgb('; part of that line, because you're terminating the expression with a semi-colon. If you break out the code on to separate lines you can see the issue a little more clearly:
// Assignment happens, color equals 'rgb(';
var color = 'rgb(';
// Assignment does not happen, you called randomRGB(),
// but it's result does not get assigned to any variable, so color equals 'rgb(';
randomRGB() + ',';
// Same as above
randomRGB() + ',';
// Same as above
randomRGB() + ')';
// Color equals 'rgb(';
return color;
So to make it work, the expression needs to be modified a bit to concatenate the results from randomRGB() calls to your color variable.
You could go with the first option:
var color = 'rgb(' ; color += randomRGB() + ','; color += randomRGB() + ','; color += randomRGB() + ')'; return color;
Or you could do this instead:
var color = 'rgb(' + randomRGB() + ',' + randomRGB() + ',' + randomRGB() + ')'; return color;