JavaScript Performance – Difference Between for..in and for Loops

for-loopjavascriptloopsperformance

the difference (speed, performace, side effects, …) between implementations of the for loop:

between

var i;
for(i = 0; i < length; i++){ //Do something}
// more code

and

for(var i = 0; i < length; i++){ //Do something}
// more code

and

for(i = 0; i < length; i++){ //Do something}
// more code

and between

var e;
for( e in array){ //Do something}
// more code

and

for(var e in array){ //Do something}
// more code

and

for(e in array){ //Do something}
// more code

Best Answer

There is no difference.

JavaScript variables have only function scope, and although you can place a var statement in the initialisation part of a for loop in reality the declaration is "hoisted" to the top of the scope such that when your second case examples run they're treated exactly like the first cases.

EDIT: Since you updated the question after I answered, the third syntax that you added where you don't use the var keyword means the variable i (or e) will be created as a global - unless it already exists as a global in which case the existing variable will be overwritten. Global variable access is slower than local variable access.

NOTE: my interpretation of the question is that it is not comparing a standard for loop with the for..in variant, it is just compared the different variable declaration methods with each other for a standard for loop, then doing the same again for a for..in loop.