14

Possible Duplicate:
Incrementing in C++ - When to use x++ or ++x?

What is the difference between x++ and ++x ?

Community
  • 1
  • 1
steve
  • 141
  • 1
  • 1
  • 3
  • possible duplicate of [Incrementing in C++ - When to use x++ or ++x?](http://stackoverflow.com/questions/1812990/incrementing-in-c-when-to-use-x-or-x) - even though the answer is for C++, it works exactly the same in JavaScript. – casablanca Nov 15 '10 at 15:45
  • 1
    See also http://stackoverflow.com/questions/1968371/understanding-incrementing – Paul Tomblin Nov 15 '10 at 15:48
  • Wondering how someone should know that it works the same in Javascript and C++. The question was how these expressions work in Javascript. For me that is clearly not a duplicate question. Especially since as a beginner you just see language specific syntax rather than the abstract concept behind it. – Flip Aug 18 '17 at 09:35

4 Answers4

23

x++ executes the statement and then increments the value.

++x increments the value and then executes the statement.

var x = 1;
var y = x++; // y = 1, x = 2
var z = ++x; // z = 3, x = 3
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
9

x++ returns x, then increments it.

++x increments x, then returns it.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
8

++x is higher in the order of operations than x++. ++x happens prior to assignments, but x++ happens after assignments.

For exmaple:

var x = 5;
var a = x++;
// now a == 5, x == 6

And:

var x = 5;
var a = ++x;
// now a == 6, x == 6
Ben Lee
  • 52,489
  • 13
  • 125
  • 145
2

If you write y = ++x, the y variable will be assigned after incrementing x.
If you write y = x++, the y variable will be assigned before incrementing x.

If x is 1, the first one will set y to 2; the second will set y to 1.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964