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

Joe Williams
Joe Williams
4,014 Points

Why isn't the var necessary when using += in this code?

In the video, we learned that

var visitorName = prompt("What is your name?");

var message = "Hello " + visitorName; 

message +=  ". We are so glad you came to visit this page.";

console.log(message); 

can replace

var visitorName = prompt("What is your name?");

var message = "Hello " + visitorName; 

var message = message +  ". We are so glad you came to visit this page.";

console.log(message); 

David taught us that += is just as good as saying "message = message + ...." etc. etc.

Why is it, though, that when I use var that I get an error?

2 Answers

Steven Byington
Steven Byington
13,584 Points

when you say var message the first time you are setting that variable. Later when you say message += ...., you are adding to the original message variable you set.

So, when you add var message a second time, you are basically reseting the original variable.

Joe Williams
Joe Williams
4,014 Points

That makes perfect sense. Thanks!

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,253 Points

Yea Stephen's got it. It's just part of the shorthand syntax. You're adding to the value that's already there and += is just saying, take what's already in the value and add to it's what's on the right of the += operator. :-)