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 Basics (Retired) Storing and Tracking Information with Variables Combining Strings

Melissa Correia
Melissa Correia
3,480 Points

I thought that adding strings to update the variable (message+=) overwrites what was already declared earlier. Why not?

var name = "Dave"; var message = "Hello " + name; message += "how are you?";

I'm not understanding this concept of updating the variable. Why is the string not overwritten by the update? Why is it just added to?

2 Answers

Steven Parker
Steven Parker
230,274 Points

There's two kinds of assignment, so you get to pick the behavior you want. Ordinary assignment using just an equal sign ("=") will replace any previous content with the new string. But the special cancatenating assignment operator ("+=") retains the existing content and adds the new string to it.

Melissa Correia
Melissa Correia
3,480 Points

Thank you - that makes sense.

So the variable would remain untouched. The string is not added, correct?

Steven Parker
Steven Parker
230,274 Points

The variable is changed either way. In a normal assignment, it gets completely new contents. With a concatenating assignment, new content is added on to what it had already.

Thanks, Steven! That makes sense.

To add up of what Steven explained, take it that the equal sign operator (=) override a value using the same variable and the plus and equal ( +=) update using the same variable.