Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does for...in loop iterate through function names

While testing some JavaScrpt code in IE8 I'm experiencing some strange behaviour when doing a simple for..in loop:

var categories = ['for', 'bar', 'steam'];
for(var key in categories) {
    console.log(key);
}

Outputs:

0
1
2
forEach
map
filter
reduce
indexOf
end

Which includes the Array prototype functions, right? That's definitely not the way it should work. Why is that?

Btw, it works of course when changing the loop to for (var key=0; key < categories.length, key++).

like image 883
quape Avatar asked Oct 26 '12 07:10

quape


1 Answers

That's because you are probably using a library that extends Array.prototype. The reason it doesn't happen in other browsers is that they already support those methods natively. Since IE doesn't support it, there's some code that adds it in JS, which makes the methods enumerable.

That's one of the reasons why you shouldn't use for in with arrays.

The other is the fact that for in does not guarantee order of iteration, and though it does work in most browsers, it's explicitly left as undefined behavior by the specification. John Resig himself filed a bug against chrome http://code.google.com/p/chromium/issues/detail?id=883 and it was closed as won't fix, since there's no requirement that properties need to be ordered

Stick to using a standard loop

like image 105
Juan Mendes Avatar answered Sep 30 '22 19:09

Juan Mendes