Welcome to the Treehouse Community
Looking to learn something new?
still don't understand the ++ increment
var levelScore = 0 levelScore++ 0
var totalScore = levelScore++ 1
Why is it every time i assign the var levelScore to totalScore i get 1. But, every time i put the ++ sign before levelScore i get 2?
var totalScore = ++levelScore 2
Marissa Amaya11,782 Points
It's easier to understand if you print out the variable one right after another. It's essentially the difference between prefix and postfix.
var level_score = 0 ++level_score //equates to 1 level_score //equates to 1
This code works as you'd expect. Adding ++ before a variable increments that variable on the same line. Thus, level_score will be executed as 1 on line 2.
var level_score = 0 level_score++ //equates to 0 level_score //equates to 1
Here's where it gets a little confusing. Adding ++ after a variable still increments that variable, but NOT on the same line. The +1 gets added AFTER the line finishes executing. Thus, level_score will be executed as 0 on the second line, and its value will not change to 1 until line 3.
Hope that helps.
well the "++" operator does a addition of 1. And it depends on the place where it is.
var levelScore = 0 levelScore++ ->0 // when the operator is behind the variable the variable value is checked before it is incremented thats why you get a 0 here. It first checks the value, returns the value of it and then increments it
var totalScore = levelScore++ -> 1 //here the value is firstly checked, incremented and then set to the totalScore variable
var totalScore = ++levelScore ->2 //here the variable totalScore is firstly incremented before the value is returned which is 2
When you get to loops this example becomes more clear.
Just notice that when the operator is before the variable that variable will the incremented before the variable is set to another or a loop checks the statement; if it's after the variable is firstly incremented and then checked.
I hope this helped a bit.