Testing Properties
JavaScript objects can be thought of as sets of properties, and
it is often useful to be able to test for membership in the set—to
check whether an object has a property with a given name. You can do
this with the in
operator, with the
hasOwnProperty()
and property
IsEnumerable()
methods, or simply by
querying the property.
The in
operator expects a
property name (as a string) on its left side and an object on its
right. It returns true
if the
object has an own property or an inherited property by that
name:
var
o
=
{
x
:
1
}
"x"
in
o
;
// true: o has an own property "x"
"y"
in
o
;
// false: o doesn't have a property "y"
"toString"
in
o
;
// true: o inherits a toString property
The hasOwnProperty()
method
of an object tests whether that object has an own property with the
given name. It returns false
for
inherited properties:
var
o
=
{
x
:
1
}
o
.
hasOwnProperty
(
"x"
);
// true: o has an own property x
o
.
hasOwnProperty
(
"y"
);
// false: o doesn't have a property y
o
.
hasOwnProperty
(
"toString"
);
// false: toString is an inherited property
The propertyIsEnumerable()
refines the hasOwnProperty()
test.
It returns true
only if the named
property is an own property and its
enumerable
attribute is true
. Certain built-in properties are not
enumerable. Properties created by normal JavaScript code are
enumerable unless you’ve used one of the ECMAScript 5 methods shown
later to make them nonenumerable.
var
o
=
inherit
({
y
:
2
});
o
.
x
=
1
;
o
.
propertyIsEnumerable
(
"x"
);
// true: o has an own enumerable ...
Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.