What's the difference between ++i and i++ in JavaScript [duplicate]

Solution 1:

++i returns the value of i after it has been incremented. i++ returns the value of i before incrementing.

When the ++ comes before its operand it is called the "pre-increment" operator, and when it comes after it is called the "post-increment" operator.

This distinction is only important if you do something with the result.

var i = 0, j = 0;

alert(++i);  // alerts 1
alert(j++);  // alerts 0

One thing to note though is that even though i++ returns the value before incrementing, it still returns the value after it has been converted to a number.

So

var s = "1";
alert(typeof s++);  // alerts "number"
alert(s);  // alerts 2, not "11" as if by ("1" + 1)

Solution 2:

The same difference as any other c-style ++ incrementor.

foo = ++i is the same as:

i = i + 1;
foo = i;

foo = i++ is the same as;

foo = i;
i = i + 1;