Home

objhasOwnPropertyprop

objhasOwnPropertyprop refers to the JavaScript pattern of checking whether an object has a property as its own (not inherited) by using the hasOwnProperty method. In JavaScript, hasOwnProperty is defined on Object.prototype and returns true when the object has the specified property as an own property, rather than one inherited through the prototype chain.

Typical usage involves calling the method on the object with the property name, for example: obj.hasOwnProperty(prop).

When using this pattern, consider what counts as a property key. hasOwnProperty accepts strings and, in more

Pitfalls include prototype pollution risks and the possibility that an object’s own properties share names with

Modern alternative: in ES2022, Object.hasOwn(obj, prop) provides a static method that performs the same check without

In summary, objhasOwnPropertyprop describes the standard approach to determine if a property exists directly on an

If
obj
is
{a:1},
then
obj.hasOwnProperty('a')
yields
true,
while
obj.hasOwnProperty('toString')
yields
false
because
toString
is
inherited.
To
guard
against
cases
where
an
object
might
override
hasOwnProperty,
a
common
safe
form
is
Object.prototype.hasOwnProperty.call(obj,
prop).
recent
environments,
symbols.
Ensure
that
the
receiver
obj
is
a
non-null
object
before
calling
to
avoid
runtime
errors.
inherited
ones
in
complex
inheritance
structures.
Also,
some
environments
may
have
altered
or
shadowed
hasOwnProperty,
making
the
safe
call
form
more
reliable.
binding
concerns,
and
is
often
preferred
for
clarity
and
safety.
object,
distinguishing
it
from
inherited
properties,
with
safer
forms
and
modern
alternatives
available.