0

I typically follow Airbnb's ESLint configuration and I noticed I was getting throwing errors for using For...In loops? Why is this the case?

I've read into it a bit Here, but I would like a more detailed explanation or example.


const data = {
 color  : 'blue',
 movies : 'action',
 hobby  : 'football',
};

for (let prop in data) {
  console.log(`prop: ${prop} and value is ${data[prop]}`);
}
//Throws Guarding for in, should be wrapped in an if statement to    
//filter unwated properties from the prototype. 

Object.keys(data).forEach((element) => {
  console.log(`prop: ${element} and value is ${data[element]}`);
});
//This is Okay

TylerH
  • 20,799
  • 66
  • 75
  • 101
DanielSD
  • 73
  • 8
  • Check out [this stackover answer](http://stackoverflow.com/questions/6866411/safest-way-to-loop-over-javascript-object). I believe it is asking you to wrap the body of the block in if(data.hasOwnProperty(prop)) {} – Joe Lissner Mar 29 '17 at 00:45
  • @JoeLissner That's just as bad. Imagine the object has no `hasOwnProperty` method or a different one. – Bergi Mar 29 '17 at 00:59
  • There is nothing wrong with your code. `data`has no unwanted enumerable properties on its prototype. Disable the rule. – Bergi Mar 29 '17 at 01:00
  • 1
    http://eslint.org/docs/rules/guard-for-in – David Guan Mar 29 '17 at 01:27
  • @Bergi Are the for..in statements considered bad practice then? It sounds like if there were enumerable properties, I should have been using a different iteration to begin with. – DanielSD Mar 29 '17 at 17:07
  • 1
    @DanielSD No, `for in` is fine. Enumerable properties on prototype objects are a bad practice however, and outright harmful on `Object.prototype`. As long as you are only enumerating normal `Object`s like `data`, you are fine; if you are enumerating instances of other classes you should beware and make an explicit choice. – Bergi Mar 29 '17 at 17:20

0 Answers0