Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
220,925 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
220,925 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.