javascript i++ vs ++i

Web_Designer picture Web_Designer · Jul 29, 2011 · Viewed 93.3k times · Source

In javascript I have seen i++ used in many cases, and I understand that it adds one to the preceding value:

for (var i=1; i<=10; i++) {
  console.log(i);
}

But what happens when I do this:

++i;

And is it any different using the -- operator (besides of course that it's subtraction rather than addition)?

Answer

Guffa picture Guffa · Jul 29, 2011

The difference between i++ and ++i is the value of the expression.

The value i++ is the value of i before the increment. The value of ++i is the value of i after the increment.

Example:

var i = 42;
alert(i++); // shows 42
alert(i); // shows 43
i = 42;
alert(++i); // shows 43
alert(i); // shows 43

The i-- and --i operators works the same way.