1

I found this snippet in some documentation. Is the if statement redundant?

for (var key in contactData) {
    if (contactData.hasOwnProperty(key)) {
        // Omitted
    }
}

I tried this out in my browser console and both for loops printed out the same thing.

contactData = {};
contactData.a = 1;
contactData.b = 2;
for (var key in contactData) {
    if (contactData.hasOwnProperty(key)) {
        console.log(key);
    }
}
for (var key in contactData) {
    console.log(key);
}
Jesus is Lord
  • 14,971
  • 11
  • 66
  • 97
  • Not exactly redundant, but rather possibly harmful. What if you had a contact with the name `hasOwnProperty`? – Bergi May 15 '17 at 02:08
  • 1
    I was going to say it was duplicate of [for..in and hasOwnProperty](http://stackoverflow.com/questions/12735778/for-in-and-hasownproperty) – Theraot May 15 '17 at 02:10
  • I agree with @Theraot and disagree with @deceze♦ – Jesus is Lord May 15 '17 at 02:11
  • 1
    The check is only required as a guard to code that incorrectly/questionably adds an enumerable property to Object.prototype (in this case the object used as the source is trivially a plain object without a special prototype chain) – user2864740 May 15 '17 at 02:17

0 Answers0