I generally use the typeof
operator:
if (typeof obj.foo !== 'undefined') { // your code here }
It will return "undefined"
either if the property doesn’t exist or its value is undefined
.
(See also: Difference between undefined
and not being defined.)
There are other ways to figure out if a property exists on an object, like the hasOwnProperty
method:
if (obj.hasOwnProperty('foo')) { // your code here }
And the in
operator:
if ('foo' in obj) { // your code here }
The difference between the last two is that the hasOwnProperty
method will check if the property exist physically on the object (the property is not inherited).
The in
operator will check on all the properties reachable up in the prototype chain, e.g.:
var obj = { foo: 'bar'}; obj.hasOwnProperty('foo'); // true obj.hasOwnProperty('toString'); // false 'toString' in obj; // true
As you can see, hasOwnProperty
returns false
and the in
operator returns true
when checking the toString
method, this method is defined up in the prototype chain, because obj
inherits form Object.prototype
.