Search code examples
javascriptfor-in-loop

Why is JavaScript's For...In loop not recommended for arrays?


I read somewhere (sorry, I can't find the link) that the For...In loop is not recommended for arrays. It is said here: http://www.openjs.com/articles/for_loop.php that it is meant for associative arrays, and in http://www.w3schools.com/js/js_loop_for_in.asp that is for iterating through all the properties of an object (It does not say that it can be used on arrays). I do not know who to believe. I don't want this question to become a debate. I just want to know if I could use this in my code without unforeseen side effects. Thanks!


Solution

  • An array is an object, and array elements are simply properties with the numeric index converted to string. For example, arr[123] refers to a property "123" in the array object arr.

    The for ... in construct works on all objects, not just arrays, and that is cause for confusion.

    When somebody for ... in an array, most often the programmer intends to iterate just all the elements, even most likely in order. For example, if the array holds a bunch of numbers, then the programmer most likely intends to iterate a stream of numbers. The semantics is so similar to array iteration in other programming languages that it is very easy to get confused.

    In JavaScript, this construct does not iterate array elements in order. It iterates all the array's property names (including the names of inherited prototype functions, any properties added to it, any other non-element properties added to it etc.), and not in order at all. In earlier browsers, it will even find the property length, although in recent browsers these properties are now defined to be hidden for this exact reason -- people keep tripping on it!

    With the array of integers above, you get not a stream of numbers, but a stream of text strings. And not the element values, but the names of the properties (which are just the numeric indices not in any order). This is most likely not what the programmer means, if he/she comes from another programming language. If the elements stored in the array happen to be similar numeric values, it confuses the hell out of everybody.

    That's why you shouldn't do it. You shouldn't use a language construct that looks like it does obvious things, but actually does things that are completely different. It creates bugs that are very obscure and very difficult to find.