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, Part 2

+= 'string' vs + var + 'string'

in the videos dave tends to do this

html +=
'<p style="background: '
html += rgbColor()
html += ';" class="color"> '
html += rgbColor()
html += '</p>'

I noticed in php they do this

html +=
'<p style="background: '
+ rgbColor()
+ ';" class="color"> '
+ rgbColor()
+ '</p>'

and it seems to work just as well here. I like it better. any reason NOT to do it the second way?

Matthew Batman
Matthew Batman
30,187 Points

What Dave is actually doing is probably this:

html += '<p style="background: ';
html += rgbColor();
html += ';" class="color"> ';
html += rgbColor();
html += '</p>';

I haven't double-checked any of his videos, but he's probably writing one line at a time. In JavaScript, for your second example, you're actually executing one line that does the same as the series of lines.

I don't think there's a general reason not to do it the second way. You could probably come up with reasons in a specific situation where one is better than the other, but one isn't better than the other in some type of objective sense.

Mathew, thanks for responding. The only difference I see In my first example and and your example is line breaks. And yes, on my second example I add line breaks to help me stay organized. I would give you a "Best answer", but it looks like you responded in "Post comment" instead of as an answer. If you re-post it as an answer I can give you the thumbs up !

1 Answer

Steven Parker
Steven Parker
231,269 Points

There are many choices to be made in programming, not every case has a clearly "right" way.

In this situation, the final value of "html" is the same whether you build it incrementally or all at once with a single large statement.

:information_source: While it is good practice to end statements with semicolons, they are optional when the statement is the last thing on a line.

Thanks Steve, you're always awesome!