Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does x++ in JavaScript do?

Tags:

javascript

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?

like image 607
Yunhan Li Avatar asked Oct 18 '25 14:10

Yunhan Li


1 Answers

y++ 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;
like image 197
Barmar Avatar answered Oct 21 '25 05:10

Barmar