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

Why doesn't using the 'message +=' more than once, for eg. three times, repeat that message three times as well?

I'm on the javascript basics course and learned that I can add strings together with a variable name by adding +=. However, in the tutorial, it's showing me to that I can use this more than once, like for example, message +=. After writing it, I expected for the message to be repeated the same amount of times as I wrote it, but this wasn't the case. Why?

2 Answers

I'm not entirely sure what your asking, but I'll explain how the += works and that should cover it

Okay so lets say we have a message,

var message = "Hello, ";

we now want to add our name to the message, there are two main ways we could do this.

message = message + "Emily"

or

message += "Emily"

Both statements have the same outcome, but the second one is shorter.

When we use the += operator, we are telling javascript to get the old variable value (in the left), and add the value to the right.

If we were to do this mulitple times, it may look something like this:

var msg = "";
msg += "Hello, "; //msg == "Hello, "
msg += "Emily"; //msg == "Hello, Emily"
msg += "! How are you?"; //msg == "Hello, Emily! How are you?"
msg += msg; //msg == "Hello, Emily! How are you?Hello, Emily! How are you?"
jason chan
jason chan
31,009 Points

plus equal is for concatenation or increment.