Jasper Schulte
Jasper Schulte

Reputation: 7361

In a basic javascript for loop, what is the difference between ++i and i++ and which should I use

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?

Upvotes: 2

Views: 124

Answers (3)

thefourtheye
thefourtheye

Reputation: 239483

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.

Upvotes: 0

Andy897
Andy897

Reputation: 7133

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.

Upvotes: 1

Barmar
Barmar

Reputation: 781098

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.

Upvotes: 3

Related Questions