In Javascript you can use ++
operator before or after the variable name. What, if any, are the differences between these ways of incrementing a variable?
views:
50answers:
4Same 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]
As I understand them if you use them standalone they do the same thing. If you try to output the result of them as an expression then they may differ. Try alert(i++) as compared to alert(++i) to see the difference. i++ evaluates to i before the addition and ++i does the addition before evaluating.
See http://jsfiddle.net/xaDC4/ for an example.
++x
increments the value, then evaluates and stores it.x++
evaluates the value, then increments and stores it.var n=0; alert(n++); /* Shows 0, then stores n=1 */
var m=0; 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.
I was thinking about this yesterday reading this response to the question about bad assumptions in C/C++. In all cases, can we guarantee that Javascript behaves this way? Or do you think it's bad practice to use the increment statement within a more complex statement at all?