Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

14
  • 4
    What is the purpose of the check (Object.prototype.hasOwnProperty.call(obj, k))? Commented May 14, 2012 at 21:04
  • 16
    @styfle If you use a for loop to iterate over the object's properties, you also get the properties in the prototype chain. That's why checking hasOwnProperty is necessary. It only returns properties set on the object itself. Commented May 21, 2012 at 9:44
  • 15
    @styfle To make it simpler you could just write obj.hasOwnProperty(k) (I actually did this in my original post, but updated it later). hasOwnProperty is available on every object because it is part of the Object's prototype, but in the rare event that this method would be removed or overridden you might get unexpected results. By calling it from Object.prototype it makes it little more robust. The reason for using call is because you want to invoke the method on obj instead of on the prototype. Commented May 23, 2012 at 20:59
  • 6
    Would not it better to use this version ? developer.mozilla.org/en-US/docs/JavaScript/Reference/… Commented Jan 23, 2013 at 14:28
  • 1
    @XavierDelamotte You are absolutely correct. While my version works, it is very basic and ment as an example. Mozilla's code is more safe. (PS: Your link is also in the accepted answer) Commented Jan 30, 2013 at 17:39