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 propertyIsEnumerable() 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:
varo={x:1}"x"ino;// true: o has an own property "x""y"ino;// false: o doesn't have a property "y""toString"ino;// 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:
varo={x:1}o.hasOwnProperty("x");// true: o has an own property xo.hasOwnProperty("y");// false: o doesn't have a property yo.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.
varo=inherit({y:2});o.x=1;o.propertyIsEnumerable("x");// true: o has an own enumerable ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access