JS - Help understanding the answer to following piece of code

Hey all. So I’m in the field of IT, but programming is nowhere near my specialty, however, I’ve decided to try and learn some JS. Has been going fine so far, however was on the Codecademy app and the below question sprung up.

I know the answer is 12… but I’m not entirely sure how

Apologies in advance, as I know this is an incredibly simple question, but my brain just can’t work it out :wink:

number1 += number2 // same as number1 = number1 + number2 

number1 is 5 after the first reassignment (line 3)

number2 += number1 // same as number2 = number2 + number1 ---> 2 + 5 = 7

number2 is 7 after the 2nd reassignment (line 4)

So the last line adds 5 (new number1) + 7 (new number2)


Ah reading that now, it makes sense.

Thank You for the explanation :slight_smile:

1 Like

Hey there!
I know JavaScript can we a little bit messy and confusing when starting out. I’ve been there too! but don’t worry, I’ll explain this problem for you.

When we execute the code, the variable number1 is initially assigned a value of 3 and the variable number2 is initially assigned a value of 2.

Then, we update the value of number1 to be the sum of number1 and number2, which means number1 now has the value 5 (i.e., number1 += number2 is equivalent to number1 = number1 + number2, so number1 becomes 3 + 2 = 5).

Next, we update the value of number2 to be the sum of number2 and the new value of number1, which means number2 now has the value 7 (i.e., number2 += number1 is equivalent to number2 = number2 + number1, so number2 becomes 2 + 5 = 7).

Finally, we calculate the sum of number1 and number2 and store the result in the variable result. Since number1 is 5 and number2 is 7, the value of result becomes 5 + 7 = 12.

Therefore, the value of result is 12. Hope this helps, and good luck!