JavaScript Possible Iteration Over Unexpected

I have the following code:

  for (i in awards) {
         if (awards[i] instanceof Array === false) {
               console.log(awards[i]);
                httpFactory.patch(awards[i], {"read": true}, false);
             }
       }

My IDE shows this error relating to the code above:

Possible iteration over unexpected (custom / inherited) members, probably missing hasOwnProperty check

Checks for any instances of unfiltered for-in loops in JavaScript. The use of this construct results in processing inherited or unexpected properties. You need to filter own properties with hasOwnProperty() method. The validation works in JavaScript, html or jsp files.

Could you explain in more detail what is meant by this statement?


Solution 1:

The IDE is recommending that you add a test:

if (awards.hasOwnProperty(i)) {
    ...
}

inside the for loop.

I personally recommend not doing this, and disabling the warning if possible. There's simply no need in most code, and even less need in ES5 code where you can safely add non-enumerable properties to an object using Object.defineProperty

The hasOwnProperty check is only necessary if you have unsafely added new (enumerable) properties to Object.prototype, so the simplest fix is don't do that.

jQuery doesn't perform this test - they explicitly document that jQuery will break if Object.prototype is unsafely modified.

Solution 2:

Every object in javascript has prototype which has its own properties(native/inherited methods/properties) and properties which are directly attached to object itself.

When you iterate over an object, it will iterate the properties of the object itself and the properties of the prototype of the object.

So, In order to avoid iterating over the prototype, it is recommended to use hasOwnProperty method which return true only when the object has the mentioned property directly. i.e, Not inside prototype

Example

for (var k in object) {
  if (object.hasOwnProperty(k)) {
     // do your computation here.
  }
}

More details can be found here

Solution 3:

You can also refactor your loop into:

const keys = Object.keys(object);
for (const key of keys){
   // do something with object[key];
}