2

I use phpstorm and over the past half a year or so it started warning me about code like this:

    for( let key in attachmentPaths ){
      requestObject.formData.attachments.push( fs.createReadStream(attachmentPaths[key]) )
    }

Warning on [key]

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

I understand the warning message, but i don't understand how a for() like this is bad?

Surely additional checks to ensure the key exists with the object is silly as we are looping over the objects found keys..?

  • 1
    when you iterate by array this check is redundant but when you iterate by object `for .. in` will iterates by keys of object and his prototypes keys – Artem Ilchenko Nov 06 '17 at 15:11
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Iterating_over_own_properties_only – Artem Ilchenko Nov 06 '17 at 15:13
  • That warning does not appear to be appropriate any more: http://phrogz.net/death-to-hasownproperty – Bergi Nov 06 '17 at 15:18

2 Answers2

1

Surely additional checks to ensure the key exists with the object

That isn't what the error message says.

The important part is "unexpected (custom/inherited) members".

You could find yourself dealing with extra properties that you weren't expecting which are inherited on the prototype chain.

Consider:

Object.prototype.surprise = "surprise!";
var foo = {
  a: 1,
  b: 2
};
for (var bar in foo) {
  console.log(bar, foo[bar]);
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

You have to check if the object has key if you want to use for in loop. In javascript, everything is an object. You can assign functions to variables as well. With for ... in loop you are iterating all keys the object has. So if the object has a function that is assigned to a key in the object, you might try to iterate that as well (like the built in functions in strings/arrays etc.)

for( let key in attachmentPaths ){
  if(attachmentPaths.hasOwnProperty(key){
    requestObject.formData.attachments.push( fs.createReadStream(attachmentPaths[key]) )
  }
}
Koray Gocmen
  • 674
  • 6
  • 18