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!
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
What is the answer and why? Thanks.
// Enter your code below var initialScore = 8 initialScore = initialScore + 1 var totalScore = initialScore totalScore = ++initialScore
Think of variables as containers or boxes where you store things. The first line of code:
var initialScore = 8
says to create a box called initialScore and store an 8 in it. The second line of code:
initialScore = initialScore + 1
says to take initialScore out of it's box, add 1 to it and put the result back into the initialScore box. Thus initialScore will be 9 now. The third line of code:
var totalScore = initialScore
says to take the contents of initialScore (now 9), copy the value and place it into a new container called totalScore. The fourth line of code:
totalScore = ++initialScore
says to take the value of initialScore and increment it by 1, then assign that back to totalScore. So initialScore was 9 and we added 1 to it to make it 10. Then we copied the value 10 and saved it to totalScore. After the 4th line of code both variables should have the value of 10.
Mazen Halawi7,806 Points
i agree with the explanation of jonlunsford both will be equal to 10.
keep in mind there is a big difference between ++variable and variable++ ++variable will force the incrementation of the variable before you start using it in the line, whereas variable++ will cause the increment to be after you are done with the calculation on that line (more like deferred addition) example:
var sum = 20 var total = sum++ (will result in total to be 20 and sum will become 21 on the next line because the ++ will only fire after all calculations are done on this line)
var total = ++sum (will result in total and sum to be 21 on this line and afterwards because the ++ before the variable will trigger the sum to increment first and then be assigned to total)
hope its clear! cheers.