++someVariable vs. someVariable++ in JavaScript

In JavaScript you can use ++ operator before (pre-increment) or after the variable name (post-increment). What, if any, are the differences between these ways of incrementing a variable?


Solution 1:

Same as in other languages:

  • ++x (pre-increment) means "increment the variable; the value of the expression is the final value"
  • x++ (post-increment) means "remember the original value, then increment the variable; the value of the expression is the original value"

Now when used as a standalone statement, they mean the same thing:

x++;
++x;

The difference comes when you use the value of the expression elsewhere. For example:

x = 0;
y = array[x++]; // This will get array[0]

x = 0;
y = array[++x]; // This will get array[1]

Solution 2:

  • ++x increments the value, then evaluates and stores it.
  • x++ evaluates the value, then increments and stores it.
var n = 0, m = 0;

alert(n++); /* Shows 0, then stores n = 1 */
alert(++m); /* Shows 1, then stores m = 1 */

Note that there are slight performance benefits to using ++x where possible, because you read the variable, modify it, then evaluate and store it. Versus the x++ operator where you read the value, evaluate it, modify it, then store it.