2

In a basic for loop, what is the difference between

var arr = [0,1,2,3,4];
for(var i = 0, len = arr.length; i < len; ++i) {
   console.log(i);
}

and

var arr = [0,1,2,3,4];
for(var i = 0, len = arr.length; i < len; i++) {
   console.log(i);
}

(The difference is just in the ++i and i++)

I see both used everywhere. It seems to me they both produce the exact same result. If this is the case, is there a preference for either one?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Jasper Schulte
  • 7,181
  • 7
  • 23
  • 19
  • 2
    http://stackoverflow.com/questions/6867876/javascript-i-vs-i – Vic Apr 02 '14 at 17:39
  • 1
    In that case I'm sorry I was not clear about my question. I am aware about the basic difference between i++ and ++i. My question is specific to the for-loop. Does a choice for either one influence the for loop specifically? Maybe gives optimized performance? – Jasper Schulte Apr 02 '14 at 22:14

3 Answers3

3

There's no difference. The only difference between pre-increment and post-increment is if you're assigning the result to something; pre-increment assigns the new value, post-increment assigns the old value.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

pre-increment (++i) adds one to the value of i, then returns i; in contrast, i++ returns i then adds one to it, which in theory results in the creation of a temporary variable storing the value of i before the increment operation was applied.

There change i++ to ++i to optimize.

Andy897
  • 6,915
  • 11
  • 51
  • 86
  • +1, because that's one of the big differences. That said, I suspect any half-decent optimizer will turn `i++` into `++i` in these cases. I personally use `++i` because the `++` operator is the increment operator, so the whole thing reads "increment `i`." – yshavit Apr 03 '14 at 07:36
0

According to ECMA Script 5.1 Standard Specification for for loop,

f. If the second Expression is present, then.

i. Let incExprRef be the result of evaluating the second Expression.

ii. Call GetValue(incExprRef). (This value is not used.)

The expressions in alteration part are evaluated, but their values are ignored. So, ++i and i++ will not make any difference here.

Also, ++i and i++ are evaluated almost the same. So, I hardly think there will be any difference in performance front as well.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497