JSON is often assumed to have its own properties since it isn't extended from a parent object, but that assumption is not entirely correct.
Contrary to popular belief, unless an object was created using Object.create(null)
, it inherits the Object.prototype
in its prototype chain. This means that properties like hasOwnProperty
and toString
are actually defined in the prototype chain of most objects, including those created from JSON using JSON.parse
. However, standard properties defined on Object.prototype
are not enumerable, so they will not show up in a for..in
loop.
So, the decision of whether to use hasOwnProperty
depends on the context.
If you can be certain that no code (whether your own or third-party) adds enumerable properties to Object.prototype
, then there may be no need to use hasOwnProperty
in the loop.
However, if there is any uncertainty about potential additions to Object.prototype
, it might be safer to use hasOwnProperty
as a precaution. Ideally, avoiding extensions of Object.prototype
with enumerable properties and being cautious with third-party code is recommended.
Related:
- How to define method in javascript on Array.prototype and Object.prototype so that it doesn't appear in for in loop