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

Sergey Golubev
Sergey Golubev
4,106 Points

var html = ''; What does it mean to the code and why it's here?

Hi everybody, the whole course was very clear to me, but there is a one little thing i can't understand. Why do we use this "var html = ''; " and why we use it here for instance: html += '<div style="background-color:' + rgbColor + '"></div>'; .

It's a string and it's empty, however it's still a string right?

Aparently it made me really curious and i tried different things and values with it, and everytime it was a mess, so i could not understand the idea behind it.

Why it turns into a mess when we do this for example : html = '<div style="background-color:' + rgbColor + '"></div>'; . ??

Please help =)!

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! Yes, it's an empty string. But before you assign the empty string to it, it isn't. When you do something like var myString; JavaScript sets aside a piece of memory for that variable. But the variable at this point is undefined. So if you don't initialize it to an empty string and then try to append to it, it can have unexpected consequences. It's generally a good idea to initialize any variable you know will hold a string with an empty string because of this. And because this is now an empty string as opposed to undefined, you can continue appending strings to it without problem. Hope this helps! :sparkles:

edited for additional note

Also when you say html = you are overwriting the string entirely with the string on the right side of the equals. But when you do html += you are appending that string to the end of the string that was already stored there.

Sergey Golubev
Sergey Golubev
4,106 Points

Thank you, Jennifer! It does make sense for me now.