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 trialMelissa Correia
3,480 PointsI 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
231,268 PointsThere'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.
Emmanuel Tweneboah
Courses Plus Student 3,206 PointsTo 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.
Melissa Correia
3,480 PointsMelissa Correia
3,480 PointsThank you - that makes sense.
Leighton Burley
3,551 PointsLeighton Burley
3,551 PointsSo the variable would remain untouched. The string is not added, correct?
Steven Parker
231,268 PointsSteven Parker
231,268 PointsThe 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.
Leighton Burley
3,551 PointsLeighton Burley
3,551 PointsThanks, Steven! That makes sense.