-
19 May 2010, 17:24
For...in JavaScript
Many languages have
for eachloops to iterate over collections. JavaScript is a little weird in its implementation. I had forgotten about this until recently when a couple of my friends had trouble debugging a JavaScript application. While iterating over an array of elements, they were calling a method on that object that should have been there. One element, though, did not, and they couldn't figure out why.In JavaScript, you are allowed to add functions to existing objects like
Array. One common addition, is adding aremovefunction toArray. This can be done in this manner:Array.prototype.remove = function(objToRemove) { ... }Now, every array will have a remove function in addition to the functions that already exist. This is true because every object inherits from its
prototype. Adding this function and others can be extremely useful, but there is a little caveat to doing this with arrays. All of the functions ofArrayare not iterable. This allows developers to loop through all of the elements of the array using a loop looking like this:var arr = [1,2,3,4]; for(var a in arr) { doSomething(arr[a]); }It's not quite the
for...eachloop whereawould be the element, but this is still a common iteration style. But if you add that prototype line above before your loop,arr[a]will be that function. Your new function is iterable, because the point of thefor...inloop is designed to iterate over the properties of an object, not what it contains. Personally, I think this varying behavior is defective, but what are you going to do about it? Whenever I see this style of loop, I tell people to get rid of it. Go back to the old-style.