I used JSLint on a JavaScript file of mine. It threw the error:
for( ind in evtListeners ) {
Problem at line 41 character 9: The body of a for in should be
wrapped in an if statement to filter unwanted
properties from the prototype.
What does this mean?
First of all, never use a
for inloop to enumerate over an array. Never. Use good oldfor(var i = 0; i<arr.length; i++).The reason behind this is the following: each object in JavaScript has a special field called
prototype. Everything you add to that field is going to be accessible on every object of that type. Suppose you want all arrays to have a cool new function calledfilter_0that will filter zeroes out.This is a standard way to extend objects and add new methods. Lots of libraries do this.
However, let’s look at how
for inworks now:Do you see? It suddenly thinks filter_0 is another array index. Of course, it is not really a numeric index, but
for inenumerates through object fields, not just numeric indexes. So we’re now enumerating through every numeric index andfilter_0. Butfilter_0is not a field of any particular array object, every array object has this property now.Luckily, all objects have a
hasOwnPropertymethod, which checks if this field really belongs to the object itself or if it is simply inherited from the prototype chain and thus belongs to all the objects of that type.Note, that although this code works as expected for arrays, you should never, never, use
for inandfor each infor arrays. Remember thatfor inenumerates the fields of an object, not array indexes or values.