I have a very short question, but it really confused me.
var y = 3, x = y++;
What is the value of x?
I thought the answer should be 4, but actually it's 3.
Can anyone explain me the reason?
I have a very short question, but it really confused me.
var y = 3, x = y++;
What is the value of x?
I thought the answer should be 4, but actually it's 3.
Can anyone explain me the reason?
Share Improve this question edited Sep 25, 2014 at 5:44 Barmar 782k56 gold badges546 silver badges660 bronze badges asked Sep 25, 2014 at 5:42 Yunhan LiYunhan Li 1531 gold badge3 silver badges8 bronze badges 2- 1 x = y++ here the value is assigned and then incremented. this x=++y will increment and assign. – Prabhu Murthy Commented Sep 25, 2014 at 5:44
- when you do x = y++ ; first it will assign the value of y to x and then it increments. – K.D Commented Sep 25, 2014 at 5:45
4 Answers
Reset to default 11y++
is called post-increment -- it increments the variable after it returns the original value as the value of the expression. So
x = y++;
is equivalent to:
temp = y;
y = y + 1;
x = temp;
If you want to return the new value, you should use ++y
. This is called pre-increment because it increments the variable before returning it. The statement
x = ++y;
is equivalent to:
y = y + 1;
x = y;
In y++
, ++
is called "post-increment operator". It first uses the value of y
, then increments y
. In this, is contrasts to a "pre-increment operator", ++y
, which first increments y
, then returns the incremented value.
The ++
operator does two things. It increments a variable and it returns the value of the variable.
If you prefix it, ie ++y
, it will return the value after the increment (in your case, 4). If you postfix (y++
)it, it will return the value before the increment (in your case 3. Note that the value of y
is now still 4, but x was assigned before y was incremented).
var y = 3;
x = ++y;
console.log(x);
This will result in 4
This is called "pre-increment". Where it returns the incremented value .
y++
is post-increment, which returns the original value.