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 trialDaniel Hurd
12,987 PointsWhy add a variable for randomColor() in the for loop?
Hi Dave McFarland (or anyone else who knows)!
Thanks SO much for this course, it's very helpful. In The Refactoring Challenge part 2, here's the for
loop:
for (var i = 1; i <= 10; i +=1) {
rgbColor = randomColor();
html += '<div style="background-color:' + rgbColor + '"></div>';
}
So, why add a variable for the randomColor function? Wouldn't the below code be better?
for (var i = 1; i <= 10; i +=1) {
html += '<div style="background-color:' + randomColor() + '"></div>';
}
I'm curious, is adding a function to a concatenated string less stable, or maybe it's just better practice to call a function with a variable instead of the function itself? Thank you in advance!!
-Daniel H
2 Answers
Dave McFarland
Treehouse TeacherGreat question Daniel Hurd
There's more than one way to write a program. The second piece of code you list is excellent:
for (var i = 1; i <= 10; i +=1) {
html += '<div style="background-color:' + randomColor() + '"></div>';
}
It's shorter and more concise, and probably the better way to write it. I choose to use a variable just to make sure that the code was easy to understand (at least that's what I hope!)
You can certainly insert function calls within string concatenation (as long as the function returns a STRING, of course). That's a very common practice. Good job.
Nelson Lourenco
1,766 PointsI had the same question, thanks Dave!
Daniel Hurd
12,987 PointsDaniel Hurd
12,987 PointsDave McFarland -
Okay great, thank you! Wanted to ensure I wasn't missing something important. It's funny, I only had the idea to use the function within the string from the example of the other function you wrote. Seeing both options helps!
-Daniel H