3

This is related to "var" or no "var" in JavaScript's "for-in" loop? (but talks more about scope - this question IS NOT about scope)

Is looping through an object or an array more efficient/common and why?

Option 1 - Setting var outside loop

// Object
var x;
for (x in obj) { ... }
// Array
var i;
for (i = 0; i < array.length; ++i) { ... }

Option 2 - Setting var in the loop

// Object
for (var x in obj) { ... }
// Array
for (var i = 0; i < array.length; ++i) { ... }
Community
  • 1
  • 1
Lizard
  • 43,732
  • 39
  • 106
  • 167

2 Answers2

6

var gets hoisted and is scoped to the function, not the block, so the differences will be optimised away by the compiler.

The second one is marginally faster because there are fewer characters to send over the wire. This difference is not significant enough to be an influencing factor in your decision about which to use.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Actually, the fastest way is to loop BACKWARDS through the list (make sure not to do this when it affects the result). See Are loops really faster in reverse?

var i = arr.length; //or 10
while(i--)
{

}

As to the var question, you can declare it outside as long as you don't already use that name/reset the value/delete the reference afterwards.

Community
  • 1
  • 1
Riking
  • 2,389
  • 1
  • 24
  • 36