Skip to content Skip to sidebar Skip to footer

Will This For-in Loop Detection Snippet Generate Unwanted False Positives?

We all know that for-in-loops on arrays are absolutely evil. Still, they are often used and the caused errors are complicated to trace down, especially when happening browser-depen

Solution 1:

Yes. Legitimacy can often be subjective, but...

As an example, perhaps I have a sparse array, where I have only set values at the indexes with data:

var a = [];
a[123123] = "foo";
a[1233123] = "bar";

If I wanted to iterate over the elements that I defined in this array, then I would use the for...in construct. Even if I coded it defensively, your script would still trigger (a false positive)...

for (var prop in a) {
  if (a.hasOwnProperty(prop)) {
    // this is a legitimate array element
  }
}

See also Why is using "for...in" with array iteration a bad idea? for more information and opinions.

Post a Comment for "Will This For-in Loop Detection Snippet Generate Unwanted False Positives?"