4

Possible Duplicate:
Why is 'for(var item in list)' with arrays considered bad practice in JavaScript?

Is it a best practice to loop through a JavaScript array using a for..in loop?

var a = [1,2,3];
for(var x in a){
//dance
}

Or should I be using a fully written loop?

Community
  • 1
  • 1
Tegra Detra
  • 24,551
  • 17
  • 53
  • 78

6 Answers6

3

By using for..in, you are looping through all of the Array Object's properties, including inherited ones through the prototype model.

More recent browsers have a way of making properties non-Enumerable, meaning they won't show up in a for..in loop. In these browsers, you can safely use for..in on an array. HOWEVER, older browsers will behave in unexpected ways. So just because you can use for..in doesn't mean you should. In fact, you shouldn't. Use for(i=0,l=a.length; i<l; i++) for best results.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
2

Is it considered best practices to loop through an array in JavaScript using a for in loop?

No. For arrays, the recommended way is to use a normal loop without the in keyword.

for (var i = 0, len = arr.length; i <= len; i++){
  // your code here
}

On the other hand, for-in construct is useful to transverse javascript objects:

for (var i in someObj){
  if (someObj.hasOwnProperty(i)){
     // code here
  }
}

More info on MDN docs.

Alan W. Smith
  • 24,647
  • 4
  • 70
  • 96
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
2

best way (optimized) is to do

var len = a.length
for (var i = 0; i < len; i++){

}
bernabas
  • 481
  • 1
  • 4
  • 12
2

You could use anonymous function to lock array indexer inside loop.

(function() {
for (var i = 0, len = arr.length; i <= len; i++){
  // your code here
};
})();

alert(i); // undefined

It provides you better encapsulation and no way to use indexer variable out of loop

0
var a = [1,2,3];
var b = [];
for(var x in a){
  b.push(x);
}
alert(b);

Run this code in jsfiddle.net to get answer yourself. As Kolink mentioned this gives you all properties of array not just elements.

karora
  • 238
  • 1
  • 8
-2

This is definitely better than using indexes in fors as it is much more functional-like and allows for internal optimisation of the iteration process.

Aldo Stracquadanio
  • 6,167
  • 1
  • 23
  • 34