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 trialJames Ma
19,063 PointsUsed a different function and loop.
When coding this function and loop. I used different variables, and shortened the code a bit. Will i have problems in the future if lets say this script was larger?
var html = ''; var rgbColor; function getRgbColor() { var rgb = Math.floor(Math.random() * 256 ); return rgb; }
for (var i = 0; i < 10; i++){
rgbColor = 'rgb(' + getRgbColor() + ',' + getRgbColor() + ',' + getRgbColor() + ')';
html += '<div style="background-color:' + rgbColor + '"></div>';
}
document.write(html);
4 Answers
Steven Parker
231,275 PointsIt looks like when you "shortened" it you removed some of the critical elements for it to operate, or even qualify as valid syntax.
Did you test this code? Try running it and see for yourself.
Patrick McKinney
13,151 PointsI'm not sure what exactly you're trying to accomplish, but your code snippet does not work. I am guessing you want to run your getRgbColor function 3x in order to get a rgb code block that could be used as a CSS property?
Your for loop did not have an end condition and iteration.
If that is the case, the code below should work. It is better to have spaces in your code so it is readable and yourself and others can understand it. If size is an issue, you can always minify it once it's complete.
<code> "use strict";
var rgbColor;
function getRgbColor() {
var rgb = Math.floor(Math.random() * 256 );
return rgb;
}
for (var i = 0; i < 3; i++) { rgbColor = 'rgb(' + getRgbColor() + ',' + getRgbColor() + ',' + getRgbColor() + ')'; }
document.write(rgbColor); </code>
Robert Kabat
6,062 PointsI think you should not be worried. Trust me. I, on the other hand came up with different solution:
var html = ''; var rgbColor;
function generateRGB() { var color = 'rgb('; for(var i = 0; i < 3; i++) { color += Math.floor(Math.random() * 256 ); (i !== 2) ? color += ',' : color += ')'; } return color; }
for(var i = 0; i < 100; i++) {
rgbColor = generateRGB();
html += '<div style="background-color:' + rgbColor + '"></div>';
}
document.write(html);
James Ma
19,063 Pointshey, sorry. I totally forgot that I had this out there. This was posted when I first started coding, since that I have gotten to understand it better.
Robert Kabat
6,062 PointsNo worries ;)