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

When using message += string, my code fails. But when I use message = message + string, it works. Why?

This has happened multiple times with multiple sets of code. Occasionally I'll be having getting my javascript code to run, so I double and triple check it, make sure it's the same as the video, and look at the questions about the module and do googling. However, it always seems to be OK. I have found, though, that if I have something like:

message += string

and I change it to

message = message + string

my code will then work. I'm not even sure how I figured out that was my problem the first time it happened, but it's come up enough times now that I figure I should do something about it. I'm using Chrome running Windows, if that makes a difference for some reason. Any help would be appreciated, thanks.

1 Answer

Hi Joseph,

I am a bit confused where you could be going wrong with your concatenation based on the description above.

As you have rightly said.

var message;

message += string;

message = message + string;

Both of these things are exactly the same.

Have you got some working examples you could share maybe we could get to the root cause with those for you. Operating system and browser shouldn't affect how these run for you, least not from my experience.

Without specific examples I can only offer a few generic pointers:

  1. Ensure you have already previously defined your variables you wish to concatenate.
  2. Make sure your strings are contained within quote marks. "string".
  3. Don't forget your closing statement semi-colon.

Hope if nothing else these pointers are a little helpful.

Otherwise I am sure with an example we might be able to shed some more light on the issue.

Happy coding!