Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Possible Iteration Over Unexpected

Tags:

javascript

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.


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


You can also refactor your loop into:

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

Also you can get rid of the warning writing a forEach loop for a more readable and functional approach:

Object.keys(object).forEach(key => {
    // Do something with object[key]
});