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 Storing and Tracking Information with Variables Change the Value in a Variable

Gavin van Hoeijen
Gavin van Hoeijen
2,938 Points

Why won't: var score += bonusPts; not work?

I was expermenting with something that seem to make more sense in my mind.

var message = "Hello!"; console.log(message); message = "Hello from JavaScript Basics"; console.log(message);

var score = 0; score += 10; score += 5;

var bonusPts = 100; var score += bonusPts;

console.log(score);

But this does not create 115. Why is this the case?

2 Answers

Josh Thackeray
Josh Thackeray
9,895 Points

It looks like you're trying to redeclare the score variable using the var keyword. By redeclaring the variable score you are effectively removing any value you have previously set, hence why += won't work.

As you've already declared this variable with a value you shouldn't need to redeclare it, just having the following should be enough.

var message = "Hello!"; console.log(message); message = "Hello from JavaScript Basics"; console.log(message);

var score = 0; score += 10; score += 5;

var bonusPts = 100; 
score += bonusPts;

console.log(score);

Hope that helps.

Gavin van Hoeijen
Gavin van Hoeijen
2,938 Points

Hey thanks I get it now! :D