Reputation:
I have code is below :
var x = 4
var y = --x;
Why when I running the result is :
console.log("value of x: ",x); //outputs 3
console.log("value of y: ",y); //outputs 3
Why not is :
console.log("value of x: ",x); //outputs 4
console.log("value of y: ",y); //outputs 3
Upvotes: 0
Views: 80
Reputation: 7504
Here in var y = --x;
--x
will set x
to x-1
and returns the updated value.
If
x
is 3, then--x
setsx
to 2 and returns 2, whereasx--
returns 3 and, only then, setsx
to 2.
Have a look at Arithmetic operators
Upvotes: 0
Reputation: 84912
the decrement operator can be used both as a prefix, and as a suffix, and it has different behavior. In prefix position it means "decrement first, and then return the value" in postfix position it means "return the value first, and then decrement".
So var y = --x
means "change x to equal itself -1, then assign the resulting value to y"
var y = x--
means "assign the value of x to y, then change x to equal itself -1"
If you just want to do a calculation and not change what x equals, then do var y = x - 1
Upvotes: 1