javascript i++ vs ++i

One case all these answers fail to mention is what happens when i++ and ++i are used in operations with other numbers. While the whole “i++ is before, ++i is after” concept is easy to grasp when the expression is by itself, it gets much more confusing when you start combining statements. See Examples C and D below.

// Example A
var i = 42;
var a = i++; // equivalent to `var a = i; i = i+1;`
console.log(a); // 42
console.log(i); // 43

// Example B
var i = 42;
var b = ++i; // equivalent to `i = i+1; var b = i;`
console.log(b); // 43
console.log(i); // 43

// Example C
var i = 42;
var c = i++ * 2; // equivalent to `var c = i*2; i = i+1;`
console.log(c); // 84
console.log(i); // 43

// Example D
var i = 42;
var d = ++i * 2; // equivalent to `i = i+1; var d = i*2;`
console.log(d); // 86
console.log(i); // 43

Notice that in Example C, the i++ is not evaluated until after multiplication and the assignment of c. This counters the misconception that “i++ should be evaluated first in the order of operations.” So in other words the statement i++ * 2 actually calculates i * 2 before it increments i.


I thought for completeness I would add an answer specific to the first of the OP's question:

One of your example shows the i++ / ++i being used in a for loop :

for (i=1; i<=10; i++) {
  alert(i);
}

you will get 1-10 in your alerts no matter which you use. Example:

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

Paste those into a console window and you can see that they both have the same output.


++variable increments the variable, returning the new value.

variable++ increments the variable, but returns the old value.

--variable decrements the variable, returning the new value.

variable-- decrements the variable, but returns the old value.

For example:

a = 5;
b = 5;
c = ++a;
d = b++;

a is 6, b is 6, c is 6 and d is 5.

If you're not using the result, the prefix operators work equally to the postfix operators.


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.