When is hasOwnProperty
not required?
The book JavaScript: The Good Parts includes the following which says that "it is usually necessary":
The other form (called
for in
) enumerates the property names (or keys) of an object. On each iteration, another property name string from the object is assigned to the variable.It is usually necessary to test object.
hasOwnProperty(
variable)
to determine whether the property name is truly a member of the object or was found instead on the prototype chain.for (myvar in obj) { if (obj.hasOwnProperty(myvar)) { ... } }
More specifically I want to enumerate the properties of a simple dictionary-like object, which is created using Javsacript object literal syntax, for example:
var foo = { 'bar': 'baz' };
or a similar object which is created using JSON.parse
:
var foo = JSON.parse("{ 'bar': 'baz' }");
Should I use hasOwnProperty
when I do for in
on the foo
object?
Assume that this javascript is running in a random browser as part of a complex web page.
Is the answer, "In practice it is probably/usually not necessary. In theory it could be necessary if some framework or library added a property by changing Object.prototype
, but changing Object.prototype
like that would be an intrusive bad practice which any respectable framework is unlikely to do"?
Object.keys(obj).forEach(key => ...)
as it will get own properties only. – DolefulObject.keys
- with appropriate polyfill if you think you'll need to support IE8 or earlier – JacintoObject.prototype
, or something similarly important. I once found when my JavaScript was run inside SalesForce, thatfor.. in
iterated over things other than just the intended items of my data structure (can't remember whether this was an Array or Object though). – DetumescencehasOwnProperty
not being required? – FlareObject.keys
suggestion below, in some guise. – CobdenObject.prototype
. – Celievar x = ["str"]; for(var index in x) { var item = x[index]; }
In many webpages this ran fine, but we found that it wasn't always safe.for.. in
is not exactly the same as "iterate through this array". IfArray.prototype
orObject.prototype
have been modified, thenfor.. in
will iterate over the extra properties, and not just the array's contents. I suspect that the environment in which my code was run, had modifiedArray.prototype
to give it some helper functions.for..in
is sensitive to these. – DetumescenceObject.defineProperty
to make those additions non-enumerable so that they don't appear when you dofor ... in
– CelieObject.prototype
". That was correct then, but these days (when done correctly) it's perfectly safe. – Celie