JavaScript - Identify whether a property is defined and set to 'undefined', or undefined

Claudiu picture Claudiu · Dec 22, 2008 · Viewed 27.2k times · Source

Say I have the following code:

function One() {}
One.prototype.x = undefined;

function Two() {}

var o = new One();
var t = new Two();

o.x and t.x will both evaluate to undefined. o.hasOwnProperty('x') and t.hasOwnProperty('x') will both return false; the same goes for propertyIsEnumerable. Two questions:

  • Is there any way to tell that o.x is defined and set to undefined?
  • Is there ever any reason to? (should the two be semantically equivalent?)

A small caveat: doing (for propName in o) loop will yield 'x' as one of the strings, while doing it in t will not - so there IS a difference in how they're represented internally (at least in Chrome).

Answer

Greg picture Greg · Dec 22, 2008

A slightly simpler way than your method is to use the Javascript in operator

alert('x' in o); // true
alert('x' in t); // false