var x = 3;
var y = x++;
Can someone tell me why var y = 3
and x++ = 4
.
I assumed x++ = 4
therefore y = 4
but it's not.
This dummy needs help understanding why y is not 4
but 3
var x = 3;
var y = x++;
Can someone tell me why var y = 3
and x++ = 4
.
I assumed x++ = 4
therefore y = 4
but it's not.
This dummy needs help understanding why y is not 4
but 3
x++ => The ++ after the variable is the post-increment operator. It means that the variable uses the original value and then increments the value after an operation
var x=3;
var y=x++;
console.log(y)
Similarly there is a pre-increment operator that increments values first and then uses that value
var x=3;
var y=++x;
console.log(y)
Basically ++x: load x , increment, use. x++: load x , use, increment. This is the reason why x++ still gives 3. The values is first used then incremented.
Because var y = x++;
means assign value of x to y and then increment the value of x by 1.
similarly var y = ++x;
will have opposite meaning ie. increment x
first and then assign it to y
.
so.
x = 3
var y = x++; //means y = 3, x = 4;
and
x = 3
var y = ++x; //means y = 4, x = 4;
Because the ++
is after x
: javascript increment and decrement
When you use the increment/decrement operator after the operand, the value will be returned before the operand is increased/decreased.
To in crement the value before returning it, put the ++
before the variable name ++x
:
var x = 3;
var y = x++;
console.log(x,y)
var a = 3;
var b = ++a;
console.log(a,b);