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 trialJoe Williams
4,014 PointsWhy 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
13,584 Pointswhen 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.
Jonathan Grieve
Treehouse Moderator 91,253 PointsYea 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. :-)
Joe Williams
4,014 PointsThanks!
Joe Williams
4,014 PointsJoe Williams
4,014 PointsThat makes perfect sense. Thanks!