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 trialChristine Bogdan
11,349 PointsShorter code with only one variable (var html) - good practice?
I have eliminated all but var html and instead of using variables in the functions and the for loop, I've directly inserted the functions that I've declared beforehand. Question: Is my solution common practice, or is it better to use variables and a few more steps? Thanks for your input! My code looks like this:
var html = '';
function randomColor() {
return Math.floor(Math.random() * 256 );
}
function randomRGB() {
return 'rgb(' + randomColor() + ',' + randomColor() + ',' + randomColor() + ')';
}
for ( var i = 0; i <= 10; i += 1 ) {
html += '<div style="background-color:' + randomRGB() + '"></div>';
}
document.write(html);
Dave StSomeWhere
19,870 PointsFor inserting function() names instead of variables - I think it is quite common and also makes you think about using a useful/meaningful name. Is randomColor()
a good name for a value between 0 and 255?
Christine Bogdan
11,349 PointsHi Dave StSomeWhere, good point, I'll rethink the naming!
Christine Bogdan
11,349 PointsThank you Piotr Manczak!
1 Answer
Steven Parker
231,236 PointsKeeping your code concise is a very good practice except in rare cases where it impedes readability.
More often it will improve readability and efficiency, as I believe you have done here. Good job!
Christine Bogdan
11,349 PointsThanks for your feedback, Steven Parker!
Piotr Manczak
Front End Web Development Techdegree Graduate 29,324 PointsPiotr Manczak
Front End Web Development Techdegree Graduate 29,324 PointsYour code is pretty and concise. Pure beauty. Well done.