+ 43
[SOLVED] JS inconsistent variable behavior
Could someone explain this behavior in JavaScript? 1st variable (cup) is assigned a number value. 2nd variable (jar) is calculated by adding a number to 1st variable. (At this point 1st variable retains its initial value) 3rd variable (bucket) is calculated by incrementing the 1st variable. (At this point the 1st variable takes on the incremented value). Why is the behavior not consistent? If the 1st variable does not change when calculating the 2nd variable (with addition), why does the 1st variable change when calculating the 3rd variable (with increment prefix)? https://code.sololearn.com/WwfoieXIl235/?ref=app
9 Answers
+ 13
If I understand your question correctly, the syntax x++ and ++x will affect x no matter the context it's used in. In this example, ++cup will increment cup by 1 and set the value of bucket to that result, while cup + 1 will only set the value of jar to what the result of cup + 1 is.
+ 25
Great! Thank you again for your help.
Really appreciate it!
+ 9
Candyopoly When working with ++x, x++, --x, and x--, they are (to my knowledge) the only operators that will affect both variables being incremeneted/decremented in that context. Otherwise, the initial value of the variable being incremented/decremented will stay the same no matter its context (unless you're directly telling that variable otherwise)
+ 8
Its prefix. It acts as soon as you do ++variable
EDIT
It's because you used console.log to print out the result after the calculation.
Try doing a new console.log:
console.log(++cup); // output should be 3
+ 7
I think so but there might be more.
+ 5
A++ operator add one to the after by one line.
++A operator add one to the same line and in the after,too.
+ 4
var value remain there and not reset even you make another declaration.
If you use let instead, it would show you an error mention variable cannot be declared again.
0
[SOLVED] JS inconsistent variable behavior
Could someone explain this behavior in JavaScript?
1st variable (cup) is assigned a number value.
2nd variable (jar) is calculated by adding a number to 1st variable. (At this point 1st variable retains its initial value)
3rd variable (bucket) is calculated by incrementing the 1st variable. (At this point the 1st variable takes on the incremented value).
Why is the behavior not consistent?
If the 1st variable does not change when calculating the 2nd variable (with addition), why does the 1st variable change when calculating the 3rd variable (with increment prefix)?
https://youtu.be/C8Riq59Nch4