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
Jordan Stokes
Full Stack JavaScript Techdegree Graduate 27,292 PointsWhy "+=" and not "+" for the score handler
I can't understand this line here:
score: prevState.players[index].score += delta
Why is it "+=" and not "+." I tried the same code with just "+" and it didn't work. However, I don't see any reason why it wouldn't or how "+=" could even work.
If I were to create an object and assign a value within to the sum of two separate values, this is how I would do it:
let value1 = 2; let value2 = 2;
let object = { thing: value1 + value2 }
console.log(object.thing);
And the output would be "4" without the "+="
1 Answer
Aayush Mitra
24,904 PointsWhen we use += we are adding a value to the existing value. For example:
let num1 = 40;
num1 += 1;
//num1 now equals 41
We use + when we are adding to values and putting it into a new variable. For example:
let num1 = 40;
let num2 = 60;
let num3 = num1 + num2;
//num3 is equal to 100
Hope this helps! If you need a more in depth explanation please let me know. Thanks! :)
Jordan Stokes
Full Stack JavaScript Techdegree Graduate 27,292 PointsJordan Stokes
Full Stack JavaScript Techdegree Graduate 27,292 PointsI do understand the nature of + vs +=. My confusion was based on a specific situation using Express. As far as I could see, I was using += in a situation where a variable wasn't yet created:
Video Link: https://teamtreehouse.com/library/update-state-based-on-a-players-index
However, I believe I figured it out. The point is to not just set the "score" in the new object, but to also set "score" in the "prevState.players" object.